home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / cpphtp2 / cpphtp2.jar / chpt_04.gml < prev    next >
Text File  |  1998-03-03  |  145KB  |  3,396 lines

  1. <html>
  2. <chapter>
  3. <section type=Popup name=Quotes title="Quotes">
  4. <page>
  5. <i>With sobs and tears he 
  6. sorted out<p>
  7. Those of the largest size...</i> <br>
  8. Lewis Carroll<br>
  9. <br>
  10.  
  11. </page>
  12. <page>
  13. <i>Attempt the end, and 
  14. never stand to doubt;<p>
  15. Nothing's so hard, but 
  16. search will find it out.</i> <br>
  17. Robert Herrick<br>
  18. <br>
  19.  
  20. </page>
  21. <page>
  22. <i>Now go, write it before 
  23. them in a table,<p>
  24. and note it in a book.</i> <br>
  25. Isaiah 30:8<br>
  26. <br>
  27.  
  28. </page>
  29. <page>
  30. <i>'Tis in my memory lock'd,<p>
  31. And you yourself shall 
  32. keep the key of it.</i> <br>
  33. William Shakespeare<br>
  34. <br>
  35.  
  36. </page>
  37. </section>
  38. <section type=Popup name=Answers title="Answers">
  39. <page pagename="Answers 4.1">
  40. <b>Answers 4.1</b><br>
  41. a) Arrays.<br>
  42. b) Name, type.<br>
  43. c) Subscript.<br>
  44. d) Constant variable.<br>
  45. e) Sorting.<br>
  46. f) Searching.<br>
  47. g) Double-subscripted.<br>
  48. <foreign  name="exercises" url="^Exercises::c:s0p0">
  49. <br>
  50.  
  51. </page>
  52. <page pagename="Answers 4.2">
  53. <b>Answers 4.2</b><br>
  54. a)  False. An array can store only values of the same type.<br>
  55. b)  False. An array subscript should normally be an integer or an integer 
  56. expression.<br>
  57. c)  False. The remaining elements are automatically initialized to zero.<br>
  58. d)  True.<br>
  59. e)  False. Individual elements of an array are passed call-by-value. If the entire 
  60. array is passed to a function, then any modifications will be reflected in the 
  61. original.<br>
  62. <foreign  name="exercises" url="^Exercises::c:s0p2">
  63. <br>
  64.  
  65. </page>
  66. <page pagename="Answers 4.3">
  67. <b>Answers 4.3</b><br>
  68. <font size=2><br></font><font size=11><pre>
  69. a)  const int arraySize = 10;<p>
  70. b)  float fractions[ arraySize ] = { 0 };<p>
  71. c)  fractions[ 3 ]<p>
  72. d)  fractions[ 4 ]<p>
  73. e)  fractions[ 9 ] = 1.667;<p>
  74. f)  fractions[ 6 ] = 3.333;<p>
  75. g)  cout << setiosflags( ios::fixed | ios::showpoint )<p>
  76.      << setprecision( 2 ) << fractions[ 6 ] << ' '<p>
  77.      << fractions[ 9 ] << endl;<p>
  78. <i>Output:</i> 3.33 1.67.<p>
  79. </pre></font>
  80. <foreign  name="exercises" url="^Exercises::c:s0p3">
  81.  
  82. </page>
  83. <page pagename="Answers 4.3">
  84. <font size=2><br></font><font size=11><pre>
  85. h)  for ( int x = 0; x < arraySize; x++ )<p>
  86.    cout << "fractions[" << x << "] = " << fractions[ x ] <p>
  87.         << endl;<p>
  88. <i>Output:<p>
  89. </i>fractions[ 0 ] = 0<p>
  90. fractions[ 1 ] = 0<p>
  91. fractions[ 2 ] = 0<p>
  92. fractions[ 3 ] = 0<p>
  93. fractions[ 4 ] = 0<p>
  94. </pre></font>
  95. <font size=2><br></font><font size=11><pre>
  96. fractions[ 5 ] = 0<p>
  97. fractions[ 6 ] = 3.333<p>
  98. fractions[ 7 ] = 0<p>
  99. fractions[ 8 ] = 0<p>
  100. fractions[ 9 ] = 1.667<p>
  101. </pre></font>
  102. <foreign  name="exercises" url="^Exercises::c:s0p3">
  103.  
  104. </page>
  105. <page pagename="Answers 4.4">
  106. <b>Answers 4.4</b><br>
  107. <font size=2><br></font><font size=11><pre>
  108. a)<spacer width=20 height=1>int table[ arraySize ][ arraySize ];<p>
  109. </pre></font>
  110. b)  Nine.<br>
  111. <font size=2><br></font><font size=11><pre>
  112. c)  for ( x = 0; x < arraySize; x++ )<p>
  113. <spacer width=20 height=1>         for ( y = 0; y < arraySize; y++ )<p>
  114. <spacer width=20 height=1>             table[ x ][ y ] = x + y;<p>
  115. d)  cout << "     [0]  [1]  [2]" << endl;<p>
  116. <spacer width=20 height=1>for ( int x = 0; x < arraySize; x++ ) {<p>
  117. <spacer width=20 height=1>   cout << '[' << x << "] ";<p>
  118. <spacer width=20 height=1>   for ( int y = 0; y < arraySize; y++ )<p>
  119. </pre></font>
  120. <foreign </i>>
  121. <foreign  name="exercises" url="^Exercises::c:s0p5">
  122.  
  123. </page>
  124. <page pagename="Answers 4.4">
  125. <font size=2><br></font><font size=11><pre>
  126. <spacer width=20 height=1>     [0]  [1]  [2]<p>
  127. <spacer width=20 height=1>[0]   1    8    0<p>
  128. <spacer width=20 height=1>[1]   2    4    6<p>
  129. <spacer width=20 height=1>[2]   5    0    0<p>
  130. </pre></font>
  131. <foreign  name="exercises" url="^Exercises::c:s0p5">
  132. <br>
  133.  
  134. </page>
  135. <page pagename="Answers 4.5">
  136. <b>Answers 4.5</b><br>
  137. a)  <spacer width=20 height=1>Error: Semicolon at end of <b>#include</b> preprocessor directive.<p>
  138. <spacer width=20 height=1><spacer width=20 height=1>Correction: Eliminate semicolon.<br>
  139. b)  Error: Assigning a value to a constant variable using an assignment statement.<p>
  140. Correction: Assign a value to the constant variable in a <b>const int arraySize 
  141. </b>declaration.<br>
  142. c)  Error: Referencing an array element outside the bounds of the array ( <b>b[10] </b>).<p>
  143. Correction: Change the final value of the control variable to <b>9</b>.<br>
  144. d)  Error: Array subscripting done incorrectly.<p>
  145. Correction: Change the statement to <b>a[ 1 ][ 1 ] = 5;
  146. </b><br>
  147. <foreign  name="exercises" url="^Exercises::c:s0p7">
  148. <br>
  149.  
  150. </page>
  151. <page pagename="Answers 4.12">
  152. <b>Answers 4.12</b><br>
  153. a)  <b>int counts[ 10 ] = { 0 };</b> <br>
  154. b)  <br>
  155. <font size=2><br></font><font size=11><pre>
  156. for ( int i = 0; i < 15; ++i ) <p>
  157.    ++bonus[ i ]; <p>
  158. </pre></font>
  159. c)  <br>
  160. <font size=2><br></font><font size=11><pre>
  161. for ( int p = 0; p < 12; ++p ) <p>
  162.    cin >> monthlyTemperatures[ p ]; <p>
  163. </pre></font>
  164. d)  <br>
  165. <font size=2><br></font><font size=11><pre>
  166. for ( int u = 0; u < 5; ++u ) <p>
  167.    cout << bestScores[ u ] << '\ '; <p>
  168. </pre></font>
  169. <foreign  name="exercises" url="^Exercises::c:s0p19">
  170.  
  171. </page>
  172. <page pagename="Answer 4.10 ">
  173. <b>Answer 4.10 </b><br>
  174. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  175. the file cpphtp2/answers/P4_10.zip to your hard drive and unzip the program 
  176. code.<br>
  177. <foreign  name="exercises" url="^Exercises::c:s0p15">
  178. <br>
  179.  
  180. </page>
  181. <page pagename="Answer 4.15 ">
  182. <b>Answer 4.15 </b><br>
  183. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  184. the file cpphtp2/answers/P4_15.zip to your hard drive and unzip the program 
  185. code.<br>
  186. <foreign  name="exercises" url="^Exercises::c:s0p22">
  187. <br>
  188.  
  189. </page>
  190. <page pagename="Answer 4.20 ">
  191. <b>Answer 4.20 </b><br>
  192. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  193. the file cpphtp2/answers/P4_20.zip to your hard drive and unzip the program 
  194. code.<br>
  195. <foreign  name="exercises" url="^Exercises::c:s0p28">
  196. <br>
  197.  
  198. </page>
  199. <page pagename="Answer 4.23 ">
  200. <b>Answer 4.23 </b><br>
  201. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  202. the file cpphtp2/answers/P4_23.zip to your hard drive and unzip the program 
  203. code.<br>
  204. <foreign  name="exercises" url="^Exercises::c:s0p34">
  205. <br>
  206.  
  207. </page>
  208. <page pagename="Answer 4.29 ">
  209. <b>Answer 4.29 </b><br>
  210. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  211. the file cpphtp2/answers/P4_29.zip to your hard drive and unzip the program 
  212. code.<br>
  213. <foreign  name="exercises" url="^Exercises::c:s0p53">
  214. <br>
  215.  
  216. </page>
  217. <page pagename="Answer 4.30 ">
  218. <b>Answer 4.30 </b><br>
  219. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  220. the file cpphtp2/answers/P4_30.zip to your hard drive and unzip the program 
  221. code.<br>
  222. <foreign  name="exercises" url="^Exercises::c:s0p55">
  223. <br>
  224.  
  225. </page>
  226. <page pagename="Answer 4.33 ">
  227. <b>Answer 4.33 </b><br>
  228. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  229. the file cpphtp2/answers/P4_33.zip to your hard drive and unzip the program 
  230. code.<br>
  231. <foreign  name="exercises" url="^Exercises::c:s0p61">
  232. <br>
  233.  
  234. </page>
  235. <page pagename="Answer 4.36 ">
  236. <b>Answer 4.36 </b><br>
  237. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  238. the file cpphtp2/answers/P4_36.zip to your hard drive and unzip the program 
  239. code.<br>
  240. <foreign  name="exercises" url="^Exercises::c:s0p64">
  241. <br>
  242.  
  243. </page>
  244. <page pagename="Answer 4.38 ">
  245. <b>Answer 4.38 </b><br>
  246. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  247. the file cpphtp2/answers/P4_38.zip to your hard drive and unzip the program 
  248. code.<br>
  249. <foreign  name="exercises" url="^Exercises::c:s0p66">
  250. <br>
  251.  
  252. </page>
  253. </section>
  254. <section type=Body name=Default title="4 Arrays">
  255. <page>
  256. <font size=18 bold>4 Arrays</font><hr>
  257. <a href="#s1p0">4.1<spacer width=20 height=1>Introduction</a>  <br>
  258. <a href="#s2p0">4.2<spacer width=20 height=1>Arrays</a>  <br>
  259. <a href="#s3p0">4.3<spacer width=20 height=1>Declaring Arrays</a>  <br>
  260. <a href="#s4p0">4.4<spacer width=20 height=1>Examples Using Arrays</a>  <br>
  261. <a href="#s5p0">4.5<spacer width=20 height=1>Passing Arrays to Functions</a>  <br>
  262. <a href="#s6p0">4.6<spacer width=20 height=1>Sorting Arrays</a>  <br>
  263. <a href="#s7p0">4.7<spacer width=20 height=1>Case Study: Computing Mean, Median, and Mode 
  264. Using Arrays</a>  <br>
  265. <a href="#s8p0">4.8<spacer width=20 height=1>Searching Arrays: Linear Search and Binary Search</a>  <br>
  266. <foreign  name="objectivesButton" url="^Objective::c:s0p0">
  267. <foreign  name="quotes" url="^Quotes::c:s0p0">
  268.  
  269. </page>
  270. <page>
  271. <a href="#s9p0">4.9<spacer width=20 height=1>Multiple-Subscripted Arrays</a>  <br>
  272. <a href="#s10p0">4.10<spacer width=20 height=1>Thinking About Objects: Identifying a Class's 
  273. Behaviors</a>  <br>
  274. <a href="#s11p0">4.11<spacer width=20 height=1>Elevator Laboratory Assignment 3</a>  <br>
  275. <a href="#s12p0">4.12<spacer width=20 height=1>Summary</a>  <br>
  276. <a href="^Terminology::c:s0p0">Terminology</a>  <br>
  277. <a href="^Illustration::c:s0p0">Figures</a>  <br>
  278. <foreign  name="objectivesButton" url="^Objective::c:s0p0">
  279. <foreign  name="quotes" url="^Quotes::c:s0p0">
  280.  
  281. </page>
  282. </section>
  283. <section type=Body name=Default title="4.1 Introduction">
  284. <page>
  285. <font size=18 bold>4.1 Introduction</font><hr>
  286. This chapter serves as an introduction to the important 
  287. topic of data structures. <i>Arrays</i> are data structures 
  288. consisting of related data items of the same type. In 
  289. Chapter 6, we discuss the notions of <i>structures</i> and 
  290. <i>classes</i>--each capable of holding related data items of 
  291. possibly different types. Arrays and structures are 
  292. "static" entities in that they remain the same size 
  293. throughout program execution (they may, of course, be 
  294. of automatic storage class and hence created and 
  295. destroyed each time the blocks in which they are 
  296. defined are entered and exited). In Chapter 15, we <br>
  297.  
  298. </page>
  299. <page>
  300. introduce dynamic data structures such as lists, queues, 
  301. stacks, and trees that may grow and shrink as programs 
  302. execute. The style of arrays we use in this chapter are 
  303. C-style pointer-based arrays (we will study pointers in 
  304. Chapter 5). Later in the text in Chapter 8 on "Operator 
  305. Overloading" and near the end of the book in the 
  306. chapter entitled, "The Standard Template Library," we 
  307. will cover arrays as full-fledged objects using the 
  308. techniques of object-oriented programming. We will 
  309. discover that these object-based arrays are safer and 
  310. more versatile than the C-like, pointer-based arrays we 
  311. discuss here in Chapter 4.<br>
  312.  
  313. </page>
  314. </section>
  315. <section type=Body name=Default title="4.2 Arrays">
  316. <page>
  317. <font size=18 bold>4.2 Arrays</font><hr>
  318. An array is a consecutive group of memory locations 
  319. that all have the same name and the same type. To refer 
  320. to a particular location or element in the array, we 
  321. specify the name of the array and the <i>position number</i> 
  322. of the particular element in the array.<br>
  323. <spacer width=16 height=1> <a href="^Illustration::c:s0p2"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 4.1</a> shows an integer array called c. This array 
  324. contains twelve <i>elements</i>. Any one of these elements 
  325. may be referred to by giving the name of the array 
  326. followed by the position number of the particular 
  327. element in square brackets ([]). The first element in 
  328. every array is the <i>zeroth element</i>. Thus, the first element <br>
  329.  
  330. </page>
  331. <page>
  332. of array <b>c</b> is referred to as <b>c[0]</b>, the second element of 
  333. array <b>c</b> is referred to as <b>c[1]</b>, the seventh element of 
  334. array <b>c</b> is referred to as <b>c[6]</b>, and, in general, the ith 
  335. element of array <b>c</b> is referred to as <b>c[i - 1]</b>. Array names 
  336. follow the same conventions as other variable names. <br>
  337. <spacer width=16 height=1>The position number contained within square brackets 
  338. is more formally called a <i>subscript</i>. A subscript must be 
  339. an integer or an integer expression. If a program uses an 
  340. expression as a subscript, then the expression is 
  341. evaluated to determine the subscript. For example, if we 
  342. assume that variable <b>a</b> is equal to <b>5</b> and that variable <b>b</b> 
  343. is equal to <b>6</b>, then the statement<br>
  344. <font size=2><br></font><font size=11><pre>
  345. c[ a + b ] += 2;<p>
  346. </pre></font>
  347. adds <b>2</b> to array element <b>c[ 11 ]</b>. Note that a subscripted 
  348. array name is an <i>lvalue</i>--it can be used on the left side 
  349. of an assignment.<br>
  350. <spacer width=16 height=1>Let us examine array <b>c</b> in <a href="^Illustration::c:s0p2">  <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.1</a> more closely. The 
  351. <i>name</i> of the entire array is <b>c</b>. Its twelve elements are <br>
  352.  
  353. </page>
  354. <page>
  355. named <b>c[0]</b>, <b>c[1]</b>, <b>c[2]</b>, \xc9 , <b>c[11]</b>. The <i>value</i> of <b>c[0]</b> is <b>-
  356. 45</b>, the value of <b>c[1] </b>is <b>6</b>, the value of <b>c[2]</b> is <b>0</b>, the value 
  357. of <b>c[7]</b> is <b>62</b>, and the value of <b>c[11]</b> is <b>78</b>. To print the 
  358. sum of the values contained in the first three elements 
  359. of array c, we would write<br>
  360. <font size=2><br></font><font size=11><pre>
  361. cout << c[ 0 ] + c[ 1 ] + c[ 2 ] << endl;<p>
  362. </pre></font>
  363. To divide the value of the  <a href="^Errors::c:s0p0"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>seventh element of array c 
  364. by 2 and assign the result to the variable <b>x</b>, we would 
  365. write<br>
  366. <font size=2><br></font><font size=11><pre>
  367. x = c[ 6 ] / 2;<p>
  368. </pre></font>
  369. The brackets used to enclose the subscript of an array 
  370. are actually an operator in C++. Brackets have the same <br>
  371.  
  372. </page>
  373. <page>
  374. level of precedence as parentheses. The chart in <a href="^Illustration::c:s0p3"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 
  375. 4.2</a> shows the precedence and associativity of the 
  376. operators introduced so far. They are shown top to 
  377. bottom in decreasing order of precedence with their 
  378. associativity and type. <br>
  379.  
  380. </page>
  381. <page>
  382. <b>Select the true statement(s). </b><br>
  383. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. A subscript must be an int or integer expression.">
  384. A subscript can be either of type int or type double. <br>
  385. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. The subscript must be contained in square brackets ([]).">
  386. An array element can be referenced by specifying the name of the array followed by a subscript contained in parentheses. <br>
  387. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  388. An array is a group of contiguous memory locations that all have the same name and the same type.  <br>
  389. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. They have the same precedence.">
  390. Brackets have higher precedence than parentheses. <br>
  391. <component type=button name=b label="Check Your Answer" width=125 height=24>
  392.  
  393. </page>
  394. </section>
  395. <section type=Body name=Default title="4.3 Declaring Arrays">
  396. <page>
  397. <font size=18 bold>4.3 Declaring Arrays</font><hr>
  398. Arrays occupy space in memory. The programmer 
  399. specifies the type of each element and the number of 
  400. elements required by each array so that the compiler 
  401. may reserve the appropriate amount of memory. To tell 
  402. the compiler to reserve 12 elements for integer array <b>c</b>, 
  403. the declaration<br>
  404. <font size=2><br></font><font size=11><pre>
  405. int c[ 12 ];<p>
  406. </pre></font>
  407. is used. Memory may be reserved for several arrays 
  408. with a single declaration. The following declaration 
  409. reserves 100 elements for the integer array b and 27 
  410. elements for the integer array <b>x</b>.<br>
  411.  
  412. </page>
  413. <page>
  414. <font size=2><br></font><font size=11><pre>
  415. int b[ 100 ], x[ 27 ];<p>
  416. </pre></font>
  417. Arrays may be declared to contain other data types. For 
  418. example, an array of type <b>char</b> can be used to store a 
  419. character string. Character strings and their similarity to 
  420. arrays (a relationship C++ inherited from C), and the 
  421. relationship between pointers and arrays, are discussed 
  422. in Chapter 5. After we introduce object-oriented 
  423. programming, we will consider strings as full-fledged 
  424. objects.<br>
  425.  
  426. </page>
  427. <page>
  428. <b>Select the true statement(s). </b><br>
  429. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  430. Memory may be reserved for several arrays with a single declaration.  <br>
  431. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Arrays can be declared for any data type.">
  432. Arrays can only be of data type int.  <br>
  433. <component type=button name=b label="Check Your Answer" width=125 height=24>
  434.  
  435. </page>
  436. </section>
  437. <section type=Body name=Default title="4.4 Examples Using Arrays">
  438. <page>
  439. <font size=18 bold>4.4 Examples Using Arrays</font><hr>
  440. The program in <a href="^Code::c:s0p0"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.3</a> uses a for repetition structure 
  441. to initialize the elements of a ten-element integer array 
  442. <b>n</b> to zeros, and prints the array in tabular format. The 
  443. first output statement displays the column headings for 
  444. the columns printed in the subsequent <b>for</b> structure. 
  445. Remember that <b>setw</b> specifies the field width in which 
  446. the <i>next</i> value is to be output. <br>
  447. <spacer width=16 height=1>The elements of an array can also be initialized in the 
  448. array declaration by following the declaration with an 
  449. equal sign and a comma-separated list (enclosed in 
  450. braces) of <i>initializers</i>. The program in <a href="^Code::c:s0p1"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.4</a> <br>
  451.  
  452. </page>
  453. <page>
  454. initializes an integer array with ten values and prints the 
  455. array in tabular format.<br>
  456. <spacer width=16 height=1>If there are fewer initializers than elements in the array, 
  457. the remaining elements are automatically initialized to 
  458. zero. For example, the elements of the array <b>n</b> in <a href="^Code::c:s0p0"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 
  459. 4.3</a> could have been initialized to zero with the 
  460. declaration <br>
  461. <font size=2><br></font><font size=11><pre>
  462. int n[ 10 ] = { 0 };<p>
  463. </pre></font>
  464. which explicitly initializes the first element to zero and 
  465. implicitly  <a href="^Errors::c:s0p3"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>initializes the remaining nine elements to 
  466. zero because there are fewer initializers than elements 
  467. in the array. Remember that automatic arrays are not 
  468. implicitly initialized to zero. The programmer must at <br>
  469.  
  470. </page>
  471. <page>
  472. least initialize the first element to zero for the remaining 
  473. elements to be automatically zeroed. The method used 
  474. in <a href="^Code::c:s0p0"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.3</a> can be performed repeatedly as a program 
  475. executes.<br>
  476. <spacer width=16 height=1>The following array declaration <br>
  477. <font size=2><br></font><font size=11><pre>
  478. int n[ 5 ] = { 32, 27, 64, 18, 95, 14 }; <p>
  479. </pre></font>
  480. would cause a syntax  <a href="^Errors::c:s0p2"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>error because there are 6 
  481. initializers and only 5 array elements.<br>
  482. <spacer width=16 height=1>If the array size is omitted from a declaration with an 
  483. initializer list, the number of elements in the array will 
  484. be the number of elements in the initializer list.<a href="^Perform::c:s0p0"> <img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>For 
  485. example, <br>
  486. <font size=2><br></font><font size=11><pre>
  487. int n[] = { 1, 2, 3, 4, 5 };<p>
  488. </pre></font>
  489.  
  490. </page>
  491. <page>
  492. would create a five-element array. <br>
  493. <spacer width=16 height=1>The program in <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.5</a> initializes the elements of a 
  494. ten-element array <b>s</b> to the integers <b>2, 4, 6, ..., 20</b>, and 
  495. prints the array in tabular format. These numbers are 
  496. generated by multiplying each successive value of the 
  497. loop counter by <b>2</b> and adding <b>2</b>. <br>
  498. <spacer width=16 height=1>The line <br>
  499. <font size=2><br></font><font size=11><pre>
  500. const int arraySize = 10;<p>
  501. </pre></font>
  502. uses the <b>const</b> qualifier to declare a so-called <i>constant</i> 
  503. <i>variable</i> <b>arraySize</b> the value of which is <b>10</b>. Constant 
  504. variables must be initialized with a constant expression 
  505. when they are declared and cannot be modified 
  506. thereafter (<a href="^Code::c:s0p4"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.6</a> and <a href="^Code::c:s0p3"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.7</a>). Constant variables <br>
  507.  
  508. </page>
  509. <page>
  510. are also called <i>named constants</i> or <i>read-only variables</i>. 
  511. Note that the term "constant variable" is an 
  512. oxymoron--a contradiction in terms like "jumbo 
  513. shrimp" or "freezer burn." (Please send your favorite 
  514. oxymorons to our email address listed in the Preface. 
  515. Thanks!)<br>
  516. <spacer width=16 height=1>Constant variables can be placed anywhere a <a href="^Errors::c:s0p4"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>constant 
  517. expression is expected. In <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.5</a>, constant variable 
  518. <b>arraySize</b> is used to specify the size of array <b>s</b> in the 
  519. declaration<br>
  520. <font size=2><br></font><font size=11><pre>
  521. int j, s[ arraySize ];<p>
  522. </pre></font>
  523. Using constant variables to specify array sizes makes 
  524. programs more <i>scalable</i>. In <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.5</a>, the first <b>for</b> loop <br>
  525.  
  526. </page>
  527. <page>
  528. could fill a 1000-element array by simply changing the  
  529. <a href="^Errors::c:s0p5"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>value of <b>arraySize</b> in its declaration from <b>10</b> to <b>1000</b>. If 
  530. the constant variable <b>arraySize</b> had not been used, we 
  531. would have to change the program in three separate 
  532. places to scale the program to handle 1000 array 
  533. elements. As programs get larger, this technique 
  534. becomes more useful for writing clear programs. <br>
  535. <spacer width=16 height=1>The program in  <a href="^Code::c:s0p5"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.8</a> sums the values contained in 
  536. the twelve-element integer array <b>a</b>. The statement in the 
  537. body of the <b>for</b> loop does the totaling. It is important to 
  538. remember that the values being supplied as initializers  
  539. <a href="^Engineer::c:s0p0"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>for array <b>a</b> normally would be read into the program <br>
  540.  
  541. </page>
  542. <page>
  543. from the user at the keyboard. For example, the  
  544. <a href="^Practice::c:s0p0"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>following <b>for</b> structure<br>
  545. <font size=2><br></font><font size=11><pre>
  546. for ( int j = 0; j < arraySize; j++ )<p>
  547.    cin >> a[ j ];<p>
  548. </pre></font>
  549. reads one value at a time from the keyboard and stores 
  550. the value in element <b>a[ j ]</b>.<br>
  551. <spacer width=16 height=1>Our next example uses arrays to summarize the results 
  552. of data collected in a survey. Consider the problem 
  553. statement:<br>
  554. <font size=6><br></font><indent width=16><font size=14><i>Forty students were asked to rate the quality of the food in 
  555. the student cafeteria on a scale of 1 to 10 (1 means awful 
  556. and 10 means excellent). Place the 40 responses in an integer array and summarize the results of the poll.</i></font></indent><font size=6><br></font>
  557.  
  558. </page>
  559. <page>
  560. This is a typical array application (see  <a href="^Code::c:s0p6"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.9</a>). We 
  561. wish to summarize the number of responses of each 
  562. type (i.e., 1 through 10). The array <b>responses</b> is a 40-
  563. element array of the students' responses. We use an 
  564. eleven-element array <b>frequency</b> to count the number of  
  565. <a href="^Practice::c:s0p3"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>occurrences of each response. We ignore the first 
  566. element, <b>frequency[ 0 ]</b>, because it is more logical to 
  567. have the r<a href="^Perform::c:s0p1"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>esponse 1 increment <b>frequency[ 1 ]</b> than 
  568. <b>frequency[ 0 ]</b>. This allows us to use each response 
  569. directly as a subscript on the <b>frequency</b> array. <br>
  570. <spacer width=16 height=1>The first <b>for</b> loop takes the responses one at a time from 
  571. the array <b>responses</b> and increments one of the ten <br>
  572.  
  573. </page>
  574. <page>
  575. counters (f<b>requency[ 1 ] </b>to <b>frequency[ 10 ]</b>) in the 
  576. <b>frequency</b> array. The key statement in the loop is<br>
  577. <font size=2><br></font><font size=11><pre>
  578. ++frequency[ responses[ answer ] ];<p>
  579. </pre></font>
  580. This statement increments the appropriate <b>frequency</b> 
  581. counter depending on the value of 
  582. <b>responses[ answer ]</b>. For example, when the counter 
  583. <b>answer </b>is <b>0</b>, the value of <b>responses[ answer ]</b> is <b>1</b>, so 
  584. <b>++frequency[ responses[ answer ] ]; </b>is actually 
  585. interpreted as<br>
  586. <font size=2><br></font><font size=11><pre>
  587. ++frequency[ 1 ];<p>
  588. </pre></font>
  589.  
  590. </page>
  591. <page>
  592. which increments array element one. When <b>answer</b> is 
  593. <b>1</b>, <b>responses[ answer ]</b> is <b>2</b>, so 
  594. <b>++frequency[ responses[ answer ] ]; </b>is interpreted as<br>
  595. <font size=2><br></font><font size=11><pre>
  596. ++frequency[ 2 ];<p>
  597. </pre></font>
  598. which increments array element two. When <b>answer</b> is 
  599. <b>2</b>, <b>responses[ answer ]</b> is <b>6</b>, so 
  600. <b>++frequency[ responses[ answer ] ]; </b>is interpreted as<br>
  601. <font size=2><br></font><font size=11><pre>
  602. ++frequency[ 6 ];<p>
  603. </pre></font>
  604. which increments array element six, and so on. Note 
  605. that regardless of the number of responses processed in 
  606. the survey, only an eleven-element array is required 
  607. (ignoring element zero) to summarize the results. If the <br>
  608.  
  609. </page>
  610. <page>
  611. data contained invalid values such as 13, the program 
  612. would attempt to add <b>1</b> to <b>frequency[ 13 ]</b>. This would 
  613. be  <a href="^Errors::c:s0p6"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>outside the bounds of the array. <i>C++ has no array 
  614. bounds checking to prevent the computer from referring 
  615. to an element that does not exist</i>. Thus, an executing  
  616. <a href="^Debug::c:s0p3"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>program can walk off either end of an array without 
  617. warning. The programmer should ensure that all array 
  618. references remain within the bounds of the array. C++ 
  619. <a href="^Debug::c:s0p2"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>is an extensible language. In Chapter 8, we will extend 
  620. C++ by implementing an array as a user-defined type   
  621. <a href="^Portable::c:s0p0"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a>with a class. Our new array definition will enable us to 
  622. perform many operations that are not standard for 
  623. C++'s built-in arrays. For example, we will be able to <br>
  624.  
  625. </page>
  626. <page>
  627. compare arrays directly, assign one array to another, 
  628. input and output entire arrays with <b>cin</b> and <b>cout</b>,  <a href="^Debug::c:s0p0"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a> 
  629. initialize arrays automatically, prevent access to out-of-
  630. range array elements, and change the range of 
  631. subscripts (and even their subscript type) so that the 
  632. first element of an array is not required to be element 0.<br>
  633. <spacer width=16 height=1>Our next example ( <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.10</a>) reads numbers from an 
  634. array and graphs the information in the form of a bar 
  635. chart or histogram--each number is printed, and then a 
  636. bar consisting of that many asterisks is printed beside  
  637. <a href="^Errors::c:s0p7"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>the number. The nested <b>for</b> loop actually draws the 
  638. bars. Note the use of <b>endl</b> to end a histogram bar.<br>
  639.  
  640. </page>
  641. <page>
  642. In Chapter 3 we stated that we would show a more 
  643. elegant method of writing the dice-rolling program of 
  644. Fig. 3.8. The problem was to roll a single six-sided die 
  645. 6000 times to test whether the random number 
  646. generator actually produces random numbers. An array 
  647. version of this program is shown in <a href="^Code::c:s0p8"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.11</a>.<br>
  648. <spacer width=16 height=1>To this point we have discussed only integer arrays. 
  649. However, arrays may be of any type. We now discuss  
  650. <a href="^Debug::c:s0p5"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>storing character strings in character arrays. So far, the 
  651. only string processing capability we introduced is 
  652. outputting a string with <b>cout</b> and <b><<</b>. A string such as 
  653. <b>"hello"</b> is really an array of characters. Character arrays 
  654. have several unique features.<br>
  655.  
  656. </page>
  657. <page>
  658. A character array can be initialized using a string literal. 
  659. For example, the declaration<br>
  660. <font size=2><br></font><font size=11><pre>
  661. char string1[] = "first";<p>
  662. </pre></font>
  663. initializes the elements of array <b>string1</b> to the 
  664. individual characters in the string literal <b>"first"</b>. The 
  665. size of array <b>string1</b> in the preceding declaration is 
  666. determined by the compiler based on the length of the 
  667. string. It is important to note that the string <b>"first"</b> 
  668. contains five characters <i>plus</i> a special string termination 
  669. character called the <i>null character.</i> Thus, array <b>string1</b> 
  670. actually contains six elements. The character constant 
  671. representation of the null character is <b>'\\0'</b> (backslash 
  672. followed by zero). All strings end with this character. A <br>
  673.  
  674. </page>
  675. <page>
  676. character array representing a string should always be 
  677. declared large enough to hold the number of characters 
  678. in the string and the terminating null character. <br>
  679. <spacer width=16 height=1>Character arrays also can be initialized with individual 
  680. character constants in an initializer list. The preceding 
  681. declaration is equivalent to the more tedious form<br>
  682. <font size=2><br></font><font size=11><pre>
  683. char string1[] = { 'f', 'i', 'r', 's', 't', '\\0' };<p>
  684. </pre></font>
  685. Because a string is an array of characters, we can access 
  686. individual characters in a string directly using array 
  687. subscript notation. For example, <b>string1[0]</b> is the 
  688. character <b>'f'</b> and <b>string1[3]</b> is the character <b>'s'</b>.<br>
  689.  
  690. </page>
  691. <page>
  692. We also can input a string directly into a character array 
  693. from the keyboard using <b>cin</b> and <b>>></b>. For example, the 
  694. declaration <br>
  695. <font size=2><br></font><font size=11><pre>
  696. char string2[ 20 ];<p>
  697. </pre></font>
  698. creates a character array capable of storing a string of 
  699. 19 characters and a terminating null character. The 
  700. statement<br>
  701. <font size=2><br></font><font size=11><pre>
  702. cin >> string2;<p>
  703. </pre></font>
  704. reads a string from the keyboard into <b>string2</b>. Note in 
  705. the preceding statement that only the name of the array 
  706. is  <a href="^Errors::c:s0p8"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>supplied; no information about the size of the array 
  707. is provided. It is the programmer's responsibility to <br>
  708.  
  709. </page>
  710. <page>
  711. ensure that the array into which the string is read is 
  712. capable of holding any string the user types at the 
  713. keyboard. <b>cin</b> reads characters from the keyboard until 
  714. the first whitespace character is encountered--it does 
  715. not care how large the array is. Thus, inputting data 
  716. with <b>cin</b> and <b>>></b> can insert data beyond the end of the 
  717. array (see Section 5.12 for information on preventing 
  718. insertion beyond the end of a <b>char</b> array).<br>
  719. <spacer width=16 height=1>A character array representing a null-terminated string 
  720. can be output with <b>cout</b> and <b><<</b>. The array <b>string2</b> is 
  721. printed with the statement<br>
  722. <font size=2><br></font><font size=11><pre>
  723. cout << string2 << endl;<p>
  724. </pre></font>
  725.  
  726. </page>
  727. <page>
  728. Note that <b>cout <<</b>, like <b>cin >></b>, does not care how large 
  729. the character array is. The characters of the string are 
  730. printed until a terminating null character is 
  731. encountered.<br>
  732. <spacer width=16 height=1><a href="^Code::c:s0p9"> </a> <a href="^Code::c:s0p9"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.12 </a>demonstrates initializing a character array 
  733. with a string literal, reading a string into a character 
  734. array, printing a character array as a string, and 
  735. accessing individual characters of a string. <br>
  736. <spacer width=16 height=1> <a href="^Code::c:s0p9"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.12</a> uses a <b>for</b> structure to loop through the 
  737. <b>string1</b> array and print the individual characters 
  738. separated by spaces. The condition in the <b>for</b> structure, 
  739. <b>string1[ i ] != '\\0'</b>, is true while the terminating null 
  740. character has not been encountered in the string.<br>
  741.  
  742. </page>
  743. <page>
  744. Chapter 3 discussed the storage class specifier <b>static</b>. A 
  745. <b>static</b> local variable in a function definition exists for <a href="^Perform::c:s0p2"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a> 
  746. the duration of the program but is only visible in the 
  747. function body. <br>
  748. <spacer width=16 height=1>Arrays that are declared <b>static</b> are initialized when the 
  749. program is loaded. If a <b>static</b> array is not explicitly 
  750. initialized by the programmer, that array is initialized to 
  751. zero by the compiler. <br>
  752. <spacer width=16 height=1> <a href="^Code::c:s0p10"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.13</a> demonstrates function <b>staticArrayInit 
  753. </b>with a local array declared <b>static</b> and function 
  754. <b>automaticArrayInit</b> with an automatic local array. 
  755. Function <b>staticArrayInit </b>is called twice. The <b>static</b> 
  756. local array is initialized to zero by the compiler. The <br>
  757.  
  758. </page>
  759. <page>
  760. function prints the array, adds 5 to each element, and 
  761. prints the array again. The second <a href="^Errors::c:s0p9"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>time the function is 
  762. called, the <b>static</b> array contains the values stored during 
  763. the first function call. Function <b>automaticArrayInit </b>is 
  764. also called twice. The elements of the automatic local 
  765. array are initialized with the values 1, 2, and 3. The 
  766. function prints the array, adds 5 to each element, and 
  767. prints the array again. The second time the function is 
  768. called, the array elements are re-initialized to 1, 2, and 3 
  769. because the array has automatic storage class.<br>
  770.  
  771. </page>
  772. <page>
  773. <b>Select the true statement(s). </b><br>
  774. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Array elements can be initialized in a declaration using an initializer list in braces.">
  775. Array elements cannot be initialized in a declaration.   <br>
  776. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  777. The array size can be determined by the number of elements in an initializer list.  <br>
  778. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  779. The keyword const is used to declare a constant variable.  <br>
  780. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Arrays of type char can be initialized with initializer lists or with C-style strings.">
  781. Arrays of type char cannot be initialized with initializer lists.   <br>
  782. <component type=button name=b label="Check Your Answer" width=125 height=24>
  783.  
  784. </page>
  785. </section>
  786. <section type=Body name=Default title="4.5 Passing Arrays to Functions">
  787. <page>
  788. <font size=18 bold>4.5 Passing Arrays to Functions</font><hr>
  789. To pass an array argument to a function, specify the 
  790. name of the array without any brackets. For example, if 
  791. array <b>hourlyTemperatures</b> has been declared as<br>
  792. <font size=2><br></font><font size=11><pre>
  793. int hourlyTemperatures[ 24 ];<p>
  794. </pre></font>
  795. the function call statement<br>
  796. <font size=2><br></font><font size=11><pre>
  797. modifyArray( hourlyTemperatures, 24 );<p>
  798. </pre></font>
  799. passes array <b>hourlyTemperatures</b> and its size to 
  800. function <b>modifyArray</b>. When passing an array to a 
  801. function, the array size is normally passed as well so the 
  802. function can process the specific number of elements in 
  803. the array (otherwise, we would need to build this <br>
  804.  
  805. </page>
  806. <page>
  807. knowledge into the called function itself, or worse yet 
  808. place the array size in a global variable). In Chapter 8, 
  809. when we introduce the <b>Array</b> class, we will build the 
  810. size of the array into the user-defined type--every 
  811. <b>Array</b> object that we create will "know" its own size. 
  812. Thus, when we pass an <b>Array</b> object into a function we 
  813. no longer will have to pass the size of the array as an 
  814. argument. <br>
  815. <spacer width=16 height=1>C++ automatically passes arrays to <a href="^Perform::c:s0p4"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>functions using   
  816. simulated call-by-reference--the called functions can 
  817. <a href="^Engineer::c:s0p1"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>modify the element values in the callers' original 
  818. arrays. The value of the name of the array is the address 
  819. of the first element of the array. Because the starting <br>
  820.  
  821. </page>
  822. <page>
  823. address of the array is passed, the called function knows 
  824. precisely where the array is stored. Therefore, when the 
  825. called function modifies array elements in its function 
  826. body, it is modifying the actual elements of the array in 
  827. their original memory locations. <br>
  828. <spacer width=16 height=1>Although entire arrays are passed simulated call-by-
  829. reference, individual array elements are passed call-by-
  830. value exactly as simple variables are. Such simple 
  831. single pieces of data are called <i>scalars</i> or <i>scalar 
  832. quantities</i>. To pass an element of an array to a function, 
  833. use the subscripted name of the array element as an 
  834. argument in the function call. In Chapter 5, we show <br>
  835.  
  836. </page>
  837. <page>
  838. how to simulate call-by-reference for scalars (i.e., 
  839. individual variables and array elements). <br>
  840. <spacer width=16 height=1>For a function to receive an array through a function 
  841. call, the function's parameter list must specify that an 
  842. array will be received. For example, the function header 
  843. for function <b>modifyArray</b> might be written as<br>
  844. <font size=2><br></font><font size=11><pre>
  845. void modifyArray( int b[], int arraySize )<p>
  846. </pre></font>
  847. indicating that <b>modifyArray</b> expects to receive an 
  848. array of integers in parameter b and the number of array 
  849. elements in parameter <b>arraySize</b>. The size of the array 
  850. is not required between the array brackets. If it is 
  851. included, the compiler will ignore it. Because arrays are 
  852. passed simulated call-by-reference, when the called <br>
  853.  
  854. </page>
  855. <page>
  856. function uses the array name <b>b</b>, it will in fact be 
  857. referring to the actual array in the caller (array 
  858. <b>hourlyTemperatures </b>in the preceding call). In Chapter 
  859. 5, we introduce other notations for indicating that an 
  860. array is being received by a function. As we will see, 
  861. these notations are based on the intimate relationship 
  862. between arrays and pointers.<br>
  863. <spacer width=16 height=1> <a href="^Practice::c:s0p4"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>Note the strange appearance of the function prototype 
  864. for <b>modifyArray
  865. </b><br>
  866. <font size=2><br></font><font size=11><pre>
  867. void modifyArray( int [], int );<p>
  868. </pre></font>
  869. This prototype could have been written<br>
  870. <font size=2><br></font><font size=11><pre>
  871. void modifyArray( int anyArrayName[], int anyVariableName )<p>
  872. </pre></font>
  873.  
  874. </page>
  875. <page>
  876. but as we learned in Chapter 3, C++ compilers ignore 
  877. variable names in prototypes.<br>
  878. <spacer width=16 height=1>Remember, the prototype tells the compiler the number 
  879. of arguments and the types of each argument (in the 
  880. order in which the arguments are expected to appear).<br>
  881. <spacer width=16 height=1>The program in <a href="^Code::c:s0p11"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.14</a> demonstrates the difference 
  882. between passing an entire array and passing an array 
  883. element. The program first prints the five elements of 
  884. integer array <b>a</b>. Next, <b>a</b> and its size are passed to 
  885. function <b>modifyArray</b> where each of <b>a</b>'s elements is 
  886. multiplied by 2. Then <b>a</b> is reprinted in <b>main</b>. As the 
  887. output shows, the elements of <b>a</b> are indeed modified by 
  888. <b>modifyArray</b>. Now the program prints the value of <br>
  889.  
  890. </page>
  891. <page>
  892. <b>a[3]</b> and passes it to function <b>modifyElement</b>. Function 
  893. <b>modifyElement</b> multiplies its argument by 2 and prints 
  894. the new value. Note that when <b>a[3]</b> is reprinted in 
  895. <b>main</b>, it has not been modified because individual array 
  896. elements are passed call-by-value. <br>
  897. <spacer width=16 height=1>There may be situations in your programs in which a 
  898. function should not be allowed to modify array 
  899. elements. Because arrays are always passed simulated 
  900. call-by-reference, modification of values in an array is 
  901. difficult to control. C++ provides the type qualifier 
  902. <b>const</b> that can be used to prevent modification of array 
  903. values in a function. When an array parameter is 
  904. preceded by the <b>const</b> qualifier, the elements of the <br>
  905.  
  906. </page>
  907. <page>
  908. array become constant in the function body, and any 
  909. attempt to modify an element of the array in the 
  910. function body results in a syntax error. This enables the 
  911. programmer to correct a program so it does not attempt 
  912. to modify array elements. <br>
  913. <spacer width=16 height=1> <a href="^Code::c:s0p12"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.15</a> demonstrates the  <b>const</b> <a href="^Errors::c:s0p10"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>qualifier. Function 
  914. <b>tryToModifyArray </b>is defined with parameter <b>const int 
  915. b[]</b> which specifies that array <b>b</b> is constant and cannot 
  916. be  <a href="^Engineer::c:s0p2"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>modified. Each of the three attempts by the function 
  917. to modify array elements results in the syntax error 
  918. <b>"Cannot modify a const object."</b> The <b>const</b> qualifier 
  919. will be discussed again in Chapter 7.<br>
  920.  
  921. </page>
  922. <page>
  923. <b>Select the true statement(s). </b><br>
  924. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  925. When an argument is passed call-by-value, a copy of the argument's value is passed.  <br>
  926. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  927. Call-by-reference gives called functions the ability to directly access the caller's data.  <br>
  928. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Arrays are passed call-by-reference by default. All other types of data are passed-by-value by default.">
  929. Arrays are passed call-by-value by default.   <br>
  930. <component type=button name=b label="Check Your Answer" width=125 height=24>
  931.  
  932. </page>
  933. </section>
  934. <section type=Body name=Default title="4.6 Sorting Arrays">
  935. <page>
  936. <font size=18 bold>4.6 Sorting Arrays</font><hr>
  937. <i>Sorting</i> data (i.e., placing the data into some particular 
  938. order such as ascending or descending) is one of the 
  939. most important computing applications. A bank sorts 
  940. all checks by account number so that it can prepare 
  941. individual bank statements at the end of each month. 
  942. Telephone companies sort their lists of accounts by last 
  943. name and, within that, by first name to make it easy to 
  944. find phone numbers. Virtually every organization must 
  945. sort some data and in many cases massive amounts of 
  946. data. Sorting data is an intriguing problem which has 
  947. attracted some of the most intense research efforts in <br>
  948.  
  949. </page>
  950. <page>
  951. the field of computer science. In this chapter we discuss  
  952. <i><a href="^Perform::c:s0p6"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a></i>the simplest known sorting scheme. In the exercises and 
  953. in Chapter 15, we investigate more complex schemes 
  954. that yield superior performance. <br>
  955. <spacer width=16 height=1>The program in <a href="^Code::c:s0p13"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.16</a> sorts the values of the ten-
  956. element array <b>a</b> into ascending order. The technique we 
  957. use is called the <i>bubble sort</i> or the <i>sinking sort</i> because 
  958. the smaller values gradually "bubble" their way upward 
  959. to the top of the array like air bubbles rising in water, 
  960. while the larger values sink to the bottom of the array. 
  961. The technique is to make several passes through the 
  962. array. On each pass, successive pairs of elements are 
  963. compared. If a pair is in increasing order (or the values <br>
  964.  
  965. </page>
  966. <page>
  967. are identical), we leave the values as they are. If a pair 
  968. is in decreasing order, their values are swapped in the 
  969. array.<br>
  970. <spacer width=16 height=1>First the program compares <b>a[ 0 ] </b>to <b>a[ 1 ]</b>, then <b>a[ 1 ]</b> 
  971. to <b>a[ 2 ]</b>, then <b>a[ 2 ]</b> to <b>a[ 3 ]</b>, and so on until it 
  972. completes the pass by comparing <b>a[ 8 ]</b> to <b>a[ 9 ]</b>. 
  973. Although there are 10 elements, only nine comparisons 
  974. are performed. Because of the way the successive 
  975. comparisons are made, a large value may move down 
  976. the array many positions on a single pass, but a small 
  977. value may move up only one position. On the first pass, 
  978. the largest value is guaranteed to sink to the bottom 
  979. element of the array, <b>a[ 9 ]</b>. On the second pass, the <br>
  980.  
  981. </page>
  982. <page>
  983. second largest value is guaranteed to sink to <b>a[ 8 ]</b>. On 
  984. the ninth pass, the ninth largest value sinks to <b>a[ 1 ]</b>. 
  985. This leaves the smallest value in <b>a[ 0 ]</b>, so only nine 
  986. passes are needed to sort a 10-element array.<br>
  987. <spacer width=16 height=1>The sorting is performed by the nested <b>for</b> loop. If a 
  988. swap is necessary, it is performed by the three 
  989. assignments<br>
  990. <font size=2><br></font><font size=11><pre>
  991. hold = a[ i ];<p>
  992. a[ i ] = a[ i + 1 ];<p>
  993. a[ i + 1 ] = hold;<p>
  994. </pre></font>
  995. where the extra variable <b>hold</b> temporarily stores one of 
  996. the two values being swapped. The swap cannot be 
  997. performed with only the two assignments<br>
  998.  
  999. </page>
  1000. <page>
  1001. <font size=2><br></font><font size=11><pre>
  1002. a[ i ] = a[ i + 1 ];<p>
  1003. a[ i + 1 ] = a[ i ];<p>
  1004. </pre></font>
  1005. If, for example, <b>a[i]</b> is <b>7</b> and <b>a[i + 1]</b> is <b>5</b>, after the first 
  1006. assignment both values will be <b>5</b> and the value <b>7</b> will be 
  1007. lost. Hence the need for the extra variable <b>hold</b>.<br>
  1008. <spacer width=16 height=1>The chief virtue of the bubble sort is that it is easy to 
  1009. program. However, the bubble sort runs slowly. This 
  1010. becomes apparent when sorting large arrays. In the 
  1011. exercises, we will develop more efficient versions of 
  1012. the bubble sort and investigate some far more efficient 
  1013. sorts than the bubble sort. More advanced courses 
  1014. investigate sorting and searching in greater depth. <br>
  1015.  
  1016. </page>
  1017. <page>
  1018. <b>Select the true statement(s). </b><br>
  1019. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. The bubble sort is inefficient for large arrays.">
  1020. The bubble sort is efficient for sorting large arrays.   <br>
  1021. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1022. The bubble sort algorithm specifies that to sort n numbers, n - 1 passes and n - 1 comparisons per pass must be made.  <br>
  1023. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1024. The bubble sort is also called a sink sort.  <br>
  1025. <component type=button name=b label="Check Your Answer" width=125 height=24>
  1026.  
  1027. </page>
  1028. </section>
  1029. <section type=Body name=Default title="4.7 Case Study: Computing Mean, Median, and Mode Using Arrays">
  1030. <page>
  1031. <font size=18 bold>4.7 Case Study: Computing Mean, Median, 
  1032. and Mode Using Arrays</font><hr>
  1033. We now consider a larger example. Computers are 
  1034. commonly used to compile and analyze the results of 
  1035. surveys and opinion polls. The program in <a href="^Code::c:s0p14"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.17</a> 
  1036. uses array <b>response</b> initialized with 99 responses 
  1037. (represented by constant variable <b>responseSize</b>) to a 
  1038. survey. Each of the responses is a number from 1 to 9. 
  1039. The program computes the mean, median, and mode of 
  1040. the 99 values.<br>
  1041.  
  1042. </page>
  1043. <page>
  1044. The mean is the arithmetic average of the 99 values. 
  1045. Function <b>mean</b> computes the mean by totaling the 99 
  1046. elements and dividing the result by 99.<br>
  1047. <spacer width=16 height=1>The median is the "middle value." Function <b>median</b> 
  1048. determines the median by calling function <b>bubbleSort</b> 
  1049. to sort the array of responses into ascending order, and 
  1050. picking the middle element, <b>answer[responseSize / 2]</b>, 
  1051. of the sorted array. Note that when there is an even 
  1052. number of elements, the median should be calculated as 
  1053. the mean of the two middle elements. Function <b>median</b> 
  1054. does not currently provide this capability. Function 
  1055. <b>printArray</b> is called to output the <b>response</b> array.<br>
  1056.  
  1057. </page>
  1058. <page>
  1059. The mode is the value that occurs most frequently 
  1060. among the 99 responses. Function <b>mode</b> counts the 
  1061. number of responses of each type, then selects the value 
  1062. with the greatest count. This version of function <b>mode</b> 
  1063. does not handle a tie (see  <a href="^Exercises::c:s0p21"><img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.14</a>). Function 
  1064. <b>mode</b> also produces a histogram to aid in determining 
  1065. the mode graphically.<a href="^Code::c:s0p14"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.18</a> contains a sample run of 
  1066. this program. This example includes most of the 
  1067. common manipulations usually required in array 
  1068. problems, including passing arrays to functions.<br>
  1069.  
  1070. </page>
  1071. </section>
  1072. <section type=Body name=Default title="4.8 Searching Arrays: Linear Search and Binary Search">
  1073. <page>
  1074. <font size=18 bold>4.8 Searching Arrays: Linear Search and 
  1075. Binary Search</font><hr>
  1076. Often, a programmer will be working with large 
  1077. amounts of data stored in arrays. It may be necessary to 
  1078. determine whether an array contains a value that 
  1079. matches a certain <i>key value</i>. The process of finding a 
  1080. particular element of an array is called <i>searching</i>. In 
  1081. this section we discuss two searching techniques--the 
  1082. simple <i>linear search</i> technique and the more efficient 
  1083. <i>binary search</i> technique. <a href="^Exercises::c:s0p61"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercises 4.33</a> and <a href="^Exercises::c:s0p62"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>4.34</a> at 
  1084. the end of this chapter ask you to implement recursive 
  1085. versions of the linear search and the binary search.<br>
  1086.  
  1087. </page>
  1088. <page>
  1089. The linear search (<a href="^Code::c:s0p15"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.19</a>) compares each element of 
  1090. the array with the <i>search key</i>. Since the array is not in 
  1091. any particular order, it is just as likely that the value will 
  1092. be found in the first element as the last. On average, 
  1093. therefore, the program must compare the search key 
  1094. with half the elements of the array for a value in the 
  1095. array. To determine that a value is not in the array, the 
  1096. program must compare the search key to every element 
  1097. in the array.<br>
  1098. <spacer width=16 height=1>The linear searching method works well for small 
  1099. arrays or for unsorted arrays. However, for large arrays 
  1100. linear searching is inefficient. If the array is sorted, the 
  1101. high-speed binary search technique can be used. <br>
  1102.  
  1103. </page>
  1104. <page>
  1105. The binary search algorithm eliminates one half of the 
  1106. elements in the array being searched after each 
  1107. comparison. The algorithm locates the middle element 
  1108. of the array and compares it to the search key. If they 
  1109. are equal, the search key is found and the array 
  1110. subscript of that element is returned. Otherwise, the 
  1111. problem is reduced to searching one half of the array. If 
  1112. the search key is less than the middle element of the 
  1113. array, the first half of the array is searched, otherwise 
  1114. the second half of the array is searched. If the search 
  1115. key is not the middle element in the specified subarray 
  1116. (piece of the original array), the algorithm is repeated 
  1117. on one quarter of the original array. The search <br>
  1118.  
  1119. </page>
  1120. <page>
  1121. continues until the search key is equal to the middle 
  1122. element of a subarray or until the subarray consists of 
  1123. one element that is not equal to the search key (i.e., the 
  1124. search key is not found). <br>
  1125. <spacer width=16 height=1>In a worst case scenario, searching an array of 1024 
  1126. elements will take only 10 comparisons using a binary 
  1127. search. Repeatedly dividing 1024 by 2 (because after 
  1128. each comparison we are able to eliminate half of the 
  1129. array) yields the values 512, 256, 128, 64, 32, 16, 8, 4, 
  1130. 2, and 1. The number 1024 (210) is divided by 2 only 
  1131. ten times to get the value 1. Dividing by 2 is equivalent 
  1132. to one comparison in the binary search algorithm. An 
  1133. array of 1048576 (220) elements takes a maximum of 20 <br>
  1134.  
  1135. </page>
  1136. <page>
  1137. comparisons to find the search key. An array of one 
  1138. billion elements takes a maximum of 30 comparisons to 
  1139. find the search key. This is a tremendous increase in  <a href="^Perform::c:s0p7"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar> 
  1140. </a>performance over the linear search that required 
  1141. comparing the search key to an average of half the 
  1142. elements in the array. For a one billion element array, 
  1143. this is a difference between an average of 500 million 
  1144. comparisons and a maximum of 30 comparisons! The 
  1145. maximum number of comparisons needed for the 
  1146. binary search of any sorted array can be determined by 
  1147. finding the first power of 2 greater than the number of 
  1148. elements in the array.<br>
  1149.  
  1150. </page>
  1151. <page>
  1152.  <a href="^Code::c:s0p16"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.20</a> presents the iterative version of function 
  1153. <b>binarySearch</b>. The function receives four arguments--
  1154. an integer array <b>b</b>, an integer <b>searchKey</b>, the <b>low</b> array 
  1155. subscript, and the <b>high</b> array subscript. If the search key 
  1156. does not match the middle element of a subarray, the 
  1157. <b>low</b> subscript or <b>high</b> subscript is adjusted so a smaller 
  1158. subarray can be searched. If the search key is less than 
  1159. the middle element, the <b>high</b> subscript is set to <b>middle - 
  1160. 1</b>, and the search is continued on the elements from <b>low 
  1161. to middle - 1</b>. If the search key is greater than the 
  1162. middle element, the <b>low</b> subscript is set to <b>middle + 1</b>, 
  1163. and the search is continued on the elements from 
  1164. <b>middle + 1</b> to <b>high</b>. The program uses an array of 15 <br>
  1165.  
  1166. </page>
  1167. <page>
  1168. elements. The first power of 2 greater than the number 
  1169. of elements in this array is 16 (24), so a maximum of 4 
  1170. comparisons are required to find the search key. 
  1171. Function <b>printHeader</b> outputs the array subscripts and 
  1172. function <b>printRow</b> outputs each subarray during the 
  1173. binary search process. The middle element in each 
  1174. subarray is marked with an asterisk (<b>*</b>) to indicate the 
  1175. element to which the search key is compared.<br>
  1176.  
  1177. </page>
  1178. <page>
  1179. <b>Select the true statement(s). </b><br>
  1180. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1181. The maximum number of comparisons needed for the binary search of any sorted array is the exponent for the first power of 2 greater than the number of elements in the array.  <br>
  1182. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. The process is known as searching.">
  1183. The process of locating a particular element value in an array is called sorting.   <br>
  1184. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1185. The linear search method works well for small arrays or for unsorted arrays.  <br>
  1186. <component type=button name=b label="Check Your Answer" width=125 height=24>
  1187.  
  1188. </page>
  1189. </section>
  1190. <section type=Body name=Default title="4.9 Multiple-Subscripted Arrays">
  1191. <page>
  1192. <font size=18 bold>4.9 Multiple-Subscripted Arrays</font><hr>
  1193. Arrays in C++ can have multiple subscripts. A common 
  1194. use of multiple-subscripted arrays is to represent <i>tables</i> 
  1195. of values consisting of information arranged in <i>rows</i> 
  1196. and <i>columns</i>. To identify a particular table element, we 
  1197. must specify two subscripts: The first (by convention) 
  1198. identifies the element's row, and the second (by 
  1199. convention) identifies the element's column. <br>
  1200. <spacer width=16 height=1>Tables or arrays that require two subscripts to identify a 
  1201. particular element are called <i>double-subscripted arrays</i>. 
  1202. Note that multiple-subscripted arrays can have more 
  1203. than two subscripts. C++ compilers support at least 12 <br>
  1204.  
  1205. </page>
  1206. <page>
  1207. array subscripts. <a href="^Illustration::c:s0p4"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.21</a> illustrates a double-
  1208. subscripted array, <b>a</b>. The array contains three rows and 
  1209. four columns, so it is said to be a 3-by-4 array. In 
  1210. general, an array with <i>m</i> rows and <i>n</i> columns is called 
  1211. an <i>m-by-n array</i>.<br>
  1212. <spacer width=16 height=1>Every element in array <b>a</b> is identified in  <a href="^Illustration::c:s0p4"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.21</a> by an 
  1213. element name of the form <b>a[ i ][ j ]; a</b> is the name of the 
  1214. array, and <b>i</b> and <b>j</b> are the subscripts that uniquely  
  1215. <a href="^Errors::c:s0p11"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>identify each element in <b>a</b>. Notice that the names of the 
  1216. elements in the first row all have a first subscript of <b>0</b>; 
  1217. the names of the elements in the fourth column all have 
  1218. a second subscript of <b>3</b>. <br>
  1219.  
  1220. </page>
  1221. <page>
  1222. A multiple-subscripted array can be initialized in its 
  1223. declaration much like a single subscripted array. For 
  1224. example, a double-subscripted array <b>b[ 2 ][ 2 ]</b> could be 
  1225. declared and initialized with<br>
  1226. <font size=2><br></font><font size=11><pre>
  1227. int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };<p>
  1228. </pre></font>
  1229. The values are grouped by row in braces. So, <b>1</b> and <b>2</b> 
  1230. initialize <b>b[ 0 ][ 0 ]</b> and <b>b[ 0 ][ 1 ]</b>, and <b>3</b> and <b>4</b> initialize 
  1231. <b>b[ 1 ][ 0 ]</b> and <b>b[ 1 ][ 1 ]</b>. If there are not enough 
  1232. initializers for a given row, the remaining elements of 
  1233. that row are initialized to <b>0</b>. Thus, the declaration<br>
  1234. <font size=2><br></font><font size=11><pre>
  1235. int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };<p>
  1236. </pre></font>
  1237.  
  1238. </page>
  1239. <page>
  1240. would initialize <b>b[ 0 ][ 0 ] </b>to <b>1</b>, <b>b[ 0 ][ 1 ] </b>to <b>0</b>, 
  1241. <b>b[ 1 ][ 0 ]</b> to <b>3</b> and <b>b[ 1 ][ 1 ]</b> to <b>4</b>.<br>
  1242. <spacer width=16 height=1> <a href="^Code::c:s0p17"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 4.22</a> demonstrates initializing double-
  1243. subscripted arrays in declarations. The program 
  1244. declares three arrays, each with two rows and three 
  1245. columns. The declaration of <b>array1</b> provides six 
  1246. initializers in two sublists. The first sublist initializes 
  1247. the first row of the array to the values 1, 2, and 3; and 
  1248. the second sublist initializes the second row of the array 
  1249. to the values 4, 5, and 6. If the braces around each 
  1250. sublist are removed from the <b>array1</b> initializer list, the 
  1251. compiler automatically initializes the elements of the 
  1252. first row followed by the elements of the second row. <br>
  1253.  
  1254. </page>
  1255. <page>
  1256. The declaration of <b>array2</b> provides five initializers. 
  1257. The initializers are assigned to the first row then the 
  1258. second row. Any elements that do not have an explicit 
  1259. initializer are initialized to zero automatically, so 
  1260. <b>array2[ 1 ][ 2 ]</b> is initialized to 0. <br>
  1261. <spacer width=16 height=1>The declaration of <b>array3</b> provides three initializers in 
  1262. two sublists. The sublist for the first row explicitly 
  1263. initializes the first two elements of the first row to 1 and 
  1264. 2. The third element is automatically initialized to zero. 
  1265. The sublist for the second row explicitly initializes the 
  1266. first element to 4. The last two elements are 
  1267. automatically initialized to zero. <br>
  1268.  
  1269. </page>
  1270. <page>
  1271. The program calls function <b>printArray</b> to output each 
  1272. array's elements. Notice that the function definition 
  1273. specifies the array parameter as <b>int a[][ 3 ]</b>. When we 
  1274. receive a single-subscripted array as an argument to a 
  1275. function, the array brackets are empty in the function's 
  1276. parameter list. The size of the first subscript of a 
  1277. multiple-subscripted array is not required either, but all 
  1278. subsequent subscript sizes are required. The compiler 
  1279. uses these sizes to determine the locations in memory 
  1280. of elements in multiple-subscripted arrays. All array 
  1281. elements are stored consecutively in memory regardless 
  1282. of the number of subscripts. In a double-subscripted <br>
  1283.  
  1284. </page>
  1285. <page>
  1286. array, the first row is stored in memory followed by the 
  1287. second row. <br>
  1288. <spacer width=16 height=1>Providing the subscript values in a parameter 
  1289. declaration enables the compiler to tell the function 
  1290. how to locate an element in the array. In a double-
  1291. subscripted array, each row is basically a single-
  1292. subscripted array. To locate an element in a particular 
  1293. row, the function must know exactly how many 
  1294. elements are in each row so it can skip the proper 
  1295. number of memory locations when accessing the array. 
  1296. Thus, when accessing <b>a[ 1 ][ 2 ]</b>, the function knows to 
  1297. skip the first row's three elements in memory to get to <br>
  1298.  
  1299. </page>
  1300. <page>
  1301. the second row (row 1). Then, the function accesses the 
  1302. third element of that row (element 2). <br>
  1303. <spacer width=16 height=1>Many common array manipulations use <b>for</b> repetition 
  1304. structures. For example, the following <b>for</b> structure sets 
  1305. all the elements in the third row of array <b>a</b> in <a href="^Illustration::c:s0p4"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.21</a> 
  1306. to zero:<br>
  1307. <font size=2><br></font><font size=11><pre>
  1308. for ( column = 0; column < 4; column++ )<p>
  1309.    a[ 2 ][ column ] = 0;<p>
  1310. </pre></font>
  1311. We specified the <i>third</i> row, therefore we know that the 
  1312. first subscript is always <b>2</b> (<b>0</b> is the first row subscript, 
  1313. and <b>1</b> is the second row subscript). The <b>for</b> loop varies 
  1314. only the second subscript (i.e., the column subscript). <br>
  1315.  
  1316. </page>
  1317. <page>
  1318. The preceding <b>for</b> structure is equivalent to the 
  1319. assignment statements:<br>
  1320. <font size=2><br></font><font size=11><pre>
  1321. a[ 2 ][ 0 ] = 0;<p>
  1322. a[ 2 ][ 1 ] = 0;<p>
  1323. a[ 2 ][ 2 ] = 0;<p>
  1324. a[ 2 ][ 3 ] = 0;<p>
  1325. </pre></font>
  1326. The following nested <b>for</b> structure determines the total 
  1327. of all the elements in array <b>a</b>. <br>
  1328. <font size=2><br></font><font size=11><pre>
  1329. total = 0;<p>
  1330. <p>
  1331. for ( row = 0; row < 3; row++ ) <p>
  1332.    for ( column = 0; column < 4; column++ )<p>
  1333.       total += a[ row ][ column ];<p>
  1334. </pre></font>
  1335.  
  1336. </page>
  1337. <page>
  1338. The <b>for</b> structure totals the elements of the array one 
  1339. row at a time. The outer <b>for</b> structure begins by setting 
  1340. <b>row</b> (i.e., the row subscript) to <b>0</b> so the elements of the 
  1341. first row may be totaled by the inner <b>for</b> structure. The 
  1342. outer <b>for</b> structure then increments <b>row</b> to <b>1</b>, so the 
  1343. elements of the second row can be totaled. Then, the 
  1344. outer <b>for</b> structure increments <b>row</b> to <b>2</b>, so the elements 
  1345. of the third row can be totaled. The result is printed 
  1346. when the nested for structure terminates.<br>
  1347. <spacer width=16 height=1>The program of <a href="^Code::c:s0p18"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.23</a> performs several other 
  1348. common array manipulations on 3-by-4 array 
  1349. <b>studentGrades</b>. Each row of the array represents a 
  1350. student and each column represents a grade on one of <br>
  1351.  
  1352. </page>
  1353. <page>
  1354. the four exams the students took during the semester. 
  1355. The array manipulations are performed by four 
  1356. functions. Function <b>minimum</b> determines the lowest 
  1357. grade of any student for the semester. Function 
  1358. <b>maximum</b> determines the highest grade of any student 
  1359. for the semester. Function <b>average</b> determines a 
  1360. particular student's semester average. Function 
  1361. <b>printArray</b> outputs the double-subscripted array in a 
  1362. neat, tabular format.<br>
  1363. <spacer width=16 height=1>Functions <b>minimum</b>, <b>maximum</b>, and <b>printArray</b> each 
  1364. receive three arguments--the <b>studentGrades</b> array 
  1365. (called <b>grades</b> in each function), the number of students 
  1366. (rows of the array), and the number of exams (columns <br>
  1367.  
  1368. </page>
  1369. <page>
  1370. of the array). Each function loops through array <b>grades</b> 
  1371. using nested for structures. The following nested <b>for</b> 
  1372. structure is from the function <b>minimum</b> definition:<br>
  1373. <font size=2><br></font><font size=11><pre>
  1374. for ( i = 0; i < pupils; i++ )<p>
  1375.    for ( j = 0; j < tests; j++ )<p>
  1376.       if ( grades[ i ][ j ] < lowGrade )<p>
  1377.          lowGrade = grades[ i ][ j ];<p>
  1378. </pre></font>
  1379. The outer for structure begins by setting i (i.e., the 
  1380. row subscript) to <b>0</b> so the elements of the first row can 
  1381. be compared to variable <b>lowGrade</b> in the body of the 
  1382. inner <b>for</b> structure. The inner <b>for</b> structure loops 
  1383. through the four grades of a particular row and 
  1384. compares each grade to l<b>owGrade</b>. If a grade is less <br>
  1385.  
  1386. </page>
  1387. <page>
  1388. than <b>lowGrade</b>, <b>lowGrade</b> is set to that grade. The 
  1389. outer <b>for</b> structure then increments the row subscript to 
  1390. <b>1</b>. The elements of the second row are compared to 
  1391. variable <b>lowGrade</b>. The outer <b>for</b> structure then 
  1392. increments the row subscript to <b>2</b>. The elements of the 
  1393. third row are compared to variable <b>lowGrade</b>. When 
  1394. execution of the nested structure is complete, 
  1395. <b>lowGrade</b> contains the smallest grade in the double-
  1396. subscripted array. Function <b>maximum</b> works similarly 
  1397. to function <b>minimum</b>.<br>
  1398. <spacer width=16 height=1>Function <b>average</b> takes two arguments--a single-
  1399. subscripted array of test results for a particular student 
  1400. and the number of test results in the array. When <br>
  1401.  
  1402. </page>
  1403. <page>
  1404. <b>average </b>is called, the first argument is <b>studentGrades[ 
  1405. student ]</b> which specifies that a particular row of the 
  1406. double-subscripted array <b>studentGrades</b> is to be 
  1407. passed to <b>average</b>. For example, the argument 
  1408. <b>studentGrades[ 1 ]</b> represents the four values (a single-
  1409. subscripted array of grades) stored in the second row of 
  1410. the double-subscripted array <b>studentGrades</b>. A 
  1411. double-subscripted array could be considered an array 
  1412. with elements that are single-subscripted arrays. 
  1413. Function <b>average</b> calculates the sum of the array 
  1414. elements, divides the total by the number of test results, 
  1415. and returns the floating-point result.<br>
  1416.  
  1417. </page>
  1418. <page>
  1419. <b>Select the true statement(s). </b><br>
  1420. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Multiple-subscripted arrays can have more than two subscripts.">
  1421. Multiple-subscripted arrays always have two subscripts (i.e., two dimensions).   <br>
  1422. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1423. Multiple-subscripted arrays can be initialized with initializer lists.  <br>
  1424. <component type=button name=b label="Check Your Answer" width=125 height=24>
  1425.  
  1426. </page>
  1427. </section>
  1428. <section type=Body name=Default title="4.10 Thinking About Objects: Identifying a Class's Behaviors">
  1429. <page>
  1430. <font size=18 bold>4.10 Thinking About Objects: Identifying a 
  1431. Class's Behaviors</font><hr>
  1432. In the "Thinking About Objects" sections at the ends of 
  1433. Chapters 2 and 3, we performed the first two phases of 
  1434. an object-oriented design for our elevator simulator, 
  1435. namely identifying the classes needed to implement the 
  1436. simulator and identifying the attributes of those classes. <br>
  1437. <spacer width=16 height=1>In this assignment we concentrate on determining the 
  1438. behaviors of the classes needed to implement the 
  1439. elevator simulator. In Chapter 5, we will concentrate on 
  1440. the interactions between the objects of these classes.<br>
  1441.  
  1442. </page>
  1443. <page>
  1444. Let us consider the behaviors of some real-world class 
  1445. objects. A radio's behaviors include having its station 
  1446. set and having its volume set. A car's behaviors include 
  1447. accelerating (by pressing the accelerator pedal) and 
  1448. decelerating (by pressing the brake pedal). <br>
  1449. <spacer width=16 height=1>As we will see, objects do not ordinarily perform their 
  1450. behaviors spontaneously. Rather, a specific behavior is 
  1451. normally invoked when a <i>message</i> is sent to the object, 
  1452. requesting that the object perform that specific 
  1453. behavior. This sounds like a function call--precisely 
  1454. how messages are sent to objects in C++. <br>
  1455.  
  1456. </page>
  1457. </section>
  1458. <section type=Body name=Default title="4.11 Elevator Laboratory Assignment 3 ">
  1459. <page>
  1460. <font size=18 bold>4.11 Elevator Laboratory Assignment 3 </font><hr>
  1461. 1. Continue working with the facts file you created in 
  1462. Chapter 3. You had separated the facts related to each 
  1463. class into two groups. You labeled the first group 
  1464. <i>Attributes</i> and the second group <i>Other Facts</i>. <br>
  1465. <spacer width=16 height=1>2. For each class, add a third group called <i>Behaviors</i>. 
  1466. Place in this group every behavior of a class that can be 
  1467. invoked by telling an object of that class to do 
  1468. something, i.e., by sending the object a message. For 
  1469. example, a button can be pushed (by a person), so list 
  1470. <i>pushButton</i> as a behavior of class button. Function 
  1471. <i>pushButton</i> and the other behaviors of class button are <br>
  1472.  
  1473. </page>
  1474. <page>
  1475. called <i>member functions</i> (<i>or methods</i>) of class button. 
  1476. The class's attributes (such as whether a button is "on" 
  1477. or "off") are called <i>data members</i> of class button. A 
  1478. class's member functions typically manipulate the 
  1479. class's data members (such as <i>pushButton</i> changing one 
  1480. of the button's attributes to "on"). Member functions 
  1481. also typically send messages to objects of other classes 
  1482. (such as a button object sending a <i>comeGetMe</i> message 
  1483. to summon the elevator). Assume that the elevator will 
  1484. have a button that is illuminated when someone presses 
  1485. it. When the elevator arrives at a floor, the elevator will 
  1486. want to send a <i>resetButton</i> message to turn the button's 
  1487. light off. The elevator may want to determine if a <br>
  1488.  
  1489. </page>
  1490. <page>
  1491. particular button has been pressed, so we can provide 
  1492. another behavior called <i>getButton</i> which simply 
  1493. examines a button and returns 1 or 0 to indicate that the 
  1494. button is currently "on" or "off." You will probably 
  1495. want the elevator's door to respond to messages 
  1496. <i>openDoor</i> and <i>closeDoor</i>. And so on.<br>
  1497. <spacer width=16 height=1>3. For each behavior you assign to a class, provide a 
  1498. brief description of what the behavior does. List any 
  1499. attribute changes the behavior causes, and list any 
  1500. messages the behavior sends to objects of other classes.<br>
  1501.  
  1502. </page>
  1503. <page pagename="Notes ">
  1504. <b>Notes </b><br>
  1505. 1. Begin by listing the class behaviors that are explicitly 
  1506. mentioned in the problem statement. Then list behaviors that are directly implied in the problem statement.<br>
  1507. 2. Add appropriate behaviors as it becomes apparent 
  1508. they are needed.<br>
  1509. 3. Again, system design is not a perfect and complete 
  1510. process, so do the best you can for now and be prepared 
  1511. to modify your design as you proceed with this exercise 
  1512. in subsequent chapters.<br>
  1513.  
  1514. </page>
  1515. <page pagename="Notes ">
  1516. 4. As we will see, it is difficult to glean all possible 
  1517. behaviors at this phase of the design. You will probably 
  1518. add behaviors to your classes as you continue this exercise in Chapter 5.<br>
  1519.  
  1520. </page>
  1521. </section>
  1522. <section type=Body name=Default title="4.12 Summary">
  1523. <page>
  1524. <font size=18 bold>4.12 Summary</font><hr>
  1525. <indent width=8 delay>*   C++ stores lists of values in arrays. An array is a consecutive group of related memory locations. These 
  1526. locations are related by the fact that they all have the 
  1527. same name and the same type. To refer to a particular 
  1528. location or element within the array, we specify the 
  1529. name of the array and the subscript.</indent>
  1530. <indent width=8 delay>*   A subscript may be an integer or an integer expression. Subscript expressions are evaluated to determine 
  1531. the particular element of the array.</indent>
  1532. <indent width=8 delay>*  It is important to note the difference when referring 
  1533. to the seventh element of the array as opposed to array </indent>
  1534.  
  1535. </page>
  1536. <page>
  1537. <indent width=8 delay>*   element seven. The seventh element has a subscript of 
  1538. <b>6</b>, while array element seven has a subscript of <b>7</b> (actually the eighth element of the array). This is a source of 
  1539. "off-by-one" errors.</indent>
  1540. <indent width=8 delay>*   Arrays occupy space in memory. To reserve 100 elements for integer array <b>b</b> and 27 elements for integer 
  1541. array <b>x</b>, the programmer writes</indent>
  1542. <font size=2><br></font><font size=11><pre>
  1543. int b[ 100 ], x[ 27 ];<p>
  1544. </pre></font>
  1545. <indent width=8 delay>*   An array of type <b>char</b> can be used to store a character 
  1546. string. </indent>
  1547. <indent width=8 delay>*   The elements of an array can be initialized: by declaration, by assignment, and by input.</indent>
  1548. <indent width=8 delay>*  If there are fewer initializers than elements in the </indent>
  1549.  
  1550. </page>
  1551. <page>
  1552. <indent width=8 delay>*   array, the remaining elements are initialized to zero. </indent>
  1553. <indent width=8 delay>*   C++ does not prevent referencing elements beyond 
  1554. the bounds of an array. </indent>
  1555. <indent width=8 delay>*   A character array can be initialized using a string literal.</indent>
  1556. <indent width=8 delay>*   All strings end with the null character (<b>'\\0'</b>).</indent>
  1557. <indent width=8 delay>*   Character arrays can be initialized with character 
  1558. constants in an initializer list. </indent>
  1559. <indent width=8 delay>*   Individual characters in a string stored in an array can 
  1560. be accessed directly using array subscript notation. </indent>
  1561. <indent width=8 delay>*  To pass an array to a function, the name of the array 
  1562. is passed. To pass a single element of an array to a function, simply pass the name of the array followed by the </indent>
  1563.  
  1564. </page>
  1565. <page>
  1566. <indent width=8 delay>*   subscript (contained in square brackets) of the particular element.</indent>
  1567. <indent width=8 delay>*   Arrays are passed to functions using simulated call-
  1568. by-reference--the called functions can modify the element values in the callers' original arrays. The value of 
  1569. the name of the array is the address of the first element 
  1570. of the array. Because the starting address of the array is 
  1571. passed, the called function knows precisely where the 
  1572. array is stored. </indent>
  1573. <indent width=8 delay>*   To receive an array argument, the function's parameter list must specify that an array will be received. The 
  1574. size of the array is not required in the array brackets.</indent>
  1575. <indent width=8 delay>*  C++ provides the type qualifier const that enables </indent>
  1576.  
  1577. </page>
  1578. <page>
  1579. <indent width=8 delay>*   programs to prevent modification of array values in a 
  1580. function. When an array parameter is preceded by the 
  1581. <b>const</b> qualifier, the elements of the array become constant in the function body, and any attempt to modify an 
  1582. element of the array in the function body is a syntax 
  1583. error. </indent>
  1584. <indent width=8 delay>*  An array can be sorted using the bubble-sort technique. Several passes of the array are made. On each 
  1585. pass, successive pairs of elements are compared. If a 
  1586. pair is in order (or the values are identical), it is left as 
  1587. is. If a pair is out of order, the values are swapped. For 
  1588. small arrays, the bubble sort is acceptable, but for larger 
  1589. arrays it is inefficient compared to other more sophisti</indent>
  1590.  
  1591. </page>
  1592. <page>
  1593. <indent width=8 delay>*   cated sorting algorithms. </indent>
  1594. <indent width=8 delay>*   The linear search compares each element of the array 
  1595. with the search key. If the array is not in any particular 
  1596. order, it is just as likely that the value will be found in 
  1597. the first element as the last. On average, therefore, the 
  1598. program will have to compare the search key with half 
  1599. the elements of the array. The linear searching method 
  1600. works well for small arrays and is acceptable for 
  1601. unsorted arrays. </indent>
  1602. <indent width=8 delay>*  Binary search eliminates from consideration half the 
  1603. elements in the array after each comparison by locating 
  1604. the middle element of the array and comparing it to the 
  1605. search key. If they are equal, the search key is found </indent>
  1606.  
  1607. </page>
  1608. <page>
  1609. <indent width=8 delay>*   and the array subscript of that element is returned. Otherwise, the problem is reduced to searching one half of 
  1610. the array.</indent>
  1611. <indent width=8 delay>*   In a worst case scenario, searching an array of 1024 
  1612. elements will take only 10 comparisons using a binary 
  1613. search. </indent>
  1614. <indent width=8 delay>*  Arrays may be used to represent tables of values consisting of information arranged in rows and columns. 
  1615. To identify a particular element of a table, two subscripts are specified: The first (by convention) identifies 
  1616. the row in which the element is contained, and the second (by convention) identifies the column in which the 
  1617. element is contained. Tables or arrays that require two </indent>
  1618.  
  1619. </page>
  1620. <page>
  1621. <indent width=8 delay>*   subscripts to identify a particular element are called 
  1622. double-subscripted arrays. </indent>
  1623. <indent width=8 delay>*   When we receive a single-subscripted array as an 
  1624. argument to a function, the array brackets are empty in 
  1625. the function's parameter list. The size of the first subscript of a multiple-subscripted array is not required 
  1626. either, but all subsequent subscript sizes are required. 
  1627. The compiler uses these sizes to determine the locations 
  1628. in memory of elements in multiple-subscripted arrays. </indent>
  1629. <indent width=8 delay>*   To pass one row of a double-subscripted array to a 
  1630. function that receives a single-subscripted array, simply 
  1631. pass the name of the array followed by the first subscript.</indent>
  1632.  
  1633. </page>
  1634. </section>
  1635. <section type=Popup name=Debug title="Testing">
  1636. <page>
  1637. When we study classes 
  1638. (beginning with 
  1639. Chapter 6), we will see 
  1640. how to develop a 
  1641. "smart array" which 
  1642. automatically checks 
  1643. that all subscript 
  1644. references are in 
  1645. bounds at run-time. 
  1646. Using such smart data <br>
  1647.  
  1648. </page>
  1649. <page>
  1650. types helps eliminate 
  1651. bugs.<br>
  1652. <br>
  1653.  
  1654. </page>
  1655. <page>
  1656. Programs should 
  1657. validate the correctness 
  1658. of all input values to 
  1659. prevent erroneous 
  1660. information from 
  1661. affecting a program's 
  1662. calculations.<br>
  1663. <br>
  1664.  
  1665. </page>
  1666. <page>
  1667. When looping through 
  1668. an array, the array 
  1669. subscript should never 
  1670. go below 0 and should 
  1671. always be less than the 
  1672. total number of 
  1673. elements in the array 
  1674. (one less than the size 
  1675. of the array). Make sure 
  1676. the loop terminating <br>
  1677.  
  1678. </page>
  1679. <page>
  1680. condition prevents 
  1681. accessing elements 
  1682. outside this range.<br>
  1683. <br>
  1684.  
  1685. </page>
  1686. <page>
  1687. Although it is possible 
  1688. to modify a loop 
  1689. counter in a <b>for</b> body, 
  1690. avoid doing so because 
  1691. this often leads to 
  1692. subtle bugs.<br>
  1693. <br>
  1694.  
  1695. </page>
  1696. </section>
  1697. <section type=Popup name=Terminology title="Terminology">
  1698. <page>
  1699. <font size=14>
  1700. A<br>
  1701. array 
  1702. <a href="%s1p0"><img src=iicons/bullbib.gif></a>
  1703. <a href="%s3p0"><img src=iicons/bullbib.gif></a>
  1704. <br>
  1705. array initializer list 
  1706. <a href="^Errors::c:s0p2"><img src=iicons/bullbib.gif></a>
  1707. <br>
  1708. B<br>
  1709. binary search 
  1710. <a href="%s8p0"><img src=iicons/bullbib.gif></a>
  1711. <a href="%s8p0"><img src=iicons/bullbib.gif></a>
  1712.  
  1713. <a href="%s8p1"><img src=iicons/bullbib.gif></a>
  1714. <a href="^Perform::c:s0p7"><img src=iicons/bullbib.gif></a>
  1715. <br>
  1716. bounds checking 
  1717. <a href="%s4p10"><img src=iicons/bullbib.gif></a>
  1718. <br>
  1719. bubble sort 
  1720. <a href="%s6p1"><img src=iicons/bullbib.gif></a>
  1721. <a href="%s6p4"><img src=iicons/bullbib.gif></a>
  1722. <a href="^Exercises::c:s0p17"><img src=iicons/bullbib.gif></a>
  1723. <br>
  1724. C<br>
  1725. column subscript 
  1726. <a href="^Illustration::c:s0p4"><img src=iicons/bullbib.gif></a>
  1727. <br>
  1728. <b>const</b> 
  1729. <a href="%s5p6"><img src=iicons/bullbib.gif></a>
  1730. <br>
  1731. constant variable 
  1732. <a href="%s4p3"><img src=iicons/bullbib.gif></a>
  1733. <a href="^Engineer::c:s0p0"><img src=iicons/bullbib.gif></a>
  1734.  
  1735. <a href="^Practice::c:s0p0"><img src=iicons/bullbib.gif></a>
  1736. <br>
  1737. D<br>
  1738. </font>
  1739.  
  1740. </page>
  1741. <page>
  1742. <font size=14>
  1743. double-subscripted array 
  1744.  
  1745. <a href="%s9p0"><img src=iicons/bullbib.gif></a>
  1746. <a href="%s9p3"><img src=iicons/bullbib.gif></a>
  1747. <a href="%s9p5"><img src=iicons/bullbib.gif></a>
  1748. <a href="%s9p12"><img src=iicons/bullbib.gif></a>
  1749. <a href="^Exercises::c:s0p32"><img src=iicons/bullbib.gif></a>
  1750. <br>
  1751. E<br>
  1752. element of an array 
  1753. <a href="%s2p0"><img src=iicons/bullbib.gif></a>
  1754. <br>
  1755. I<br>
  1756. initializer 
  1757. <a href="%s4p0"><img src=iicons/bullbib.gif></a>
  1758. <br>
  1759. M<br>
  1760. magic number 
  1761. <a href="^Practice::c:s0p0"><img src=iicons/bullbib.gif></a>
  1762. <br>
  1763. m-by-n array 
  1764. <a href="%s9p1"><img src=iicons/bullbib.gif></a>
  1765. <br>
  1766. multiple-subscripted 
  1767. arrays 
  1768. <a href="%s9p0"><img src=iicons/bullbib.gif></a>
  1769. <a href="%s9p0"><img src=iicons/bullbib.gif></a>
  1770. <a href="%s9p5"><img src=iicons/bullbib.gif></a>
  1771. <br>
  1772. N<br>
  1773. name of an array 
  1774. <a href="%s2p1"><img src=iicons/bullbib.gif></a>
  1775. <br>
  1776. named constant 
  1777. <a href="%s4p4"><img src=iicons/bullbib.gif></a>
  1778. <br>
  1779. </font>
  1780.  
  1781. </page>
  1782. <page>
  1783. <font size=14>
  1784. null character <b>'\\0'</b> 
  1785. <a href="%s4p13"><img src=iicons/bullbib.gif></a>
  1786. <br>
  1787. O<br>
  1788. off-by-one errors 
  1789. <a href="^Errors::c:s0p1"><img src=iicons/bullbib.gif></a>
  1790. <br>
  1791. P<br>
  1792. passing arrays to 
  1793. functions 
  1794. <a href="%s5p0"><img src=iicons/bullbib.gif></a>
  1795. <a href="%s7p2"><img src=iicons/bullbib.gif></a>
  1796. <br>
  1797. position number 
  1798. <a href="%s2p0"><img src=iicons/bullbib.gif></a>
  1799. <br>
  1800. R<br>
  1801. row subscript 
  1802. <a href="^Illustration::c:s0p4"><img src=iicons/bullbib.gif></a>
  1803. <br>
  1804. S<br>
  1805. scalable 
  1806. <a href="%s4p4"><img src=iicons/bullbib.gif></a>
  1807. <br>
  1808. scalar 
  1809. <a href="%s5p2"><img src=iicons/bullbib.gif></a>
  1810. <br>
  1811. search key 
  1812. <a href="%s8p1"><img src=iicons/bullbib.gif></a>
  1813. <a href="%s8p2"><img src=iicons/bullbib.gif></a>
  1814. <br>
  1815. searching arrays 
  1816. <a href="%s8p0"><img src=iicons/bullbib.gif></a>
  1817. <br>
  1818. </font>
  1819.  
  1820. </page>
  1821. <page>
  1822. <font size=14>
  1823. simulated call-by-
  1824. reference 
  1825. <a href="%s5p6"><img src=iicons/bullbib.gif></a>
  1826. <br>
  1827. sinking sort 
  1828. <a href="%s6p1"><img src=iicons/bullbib.gif></a>
  1829. <br>
  1830. sorting arrays 
  1831. <a href="%s6p0"><img src=iicons/bullbib.gif></a>
  1832. <br>
  1833. string literal 
  1834. <a href="%s4p13"><img src=iicons/bullbib.gif></a>
  1835. <a href="%s4p17"><img src=iicons/bullbib.gif></a>
  1836. <br>
  1837. subscript 
  1838. <a href="%s2p1"><img src=iicons/bullbib.gif></a>
  1839. <br>
  1840. T<br>
  1841. tables of values 
  1842. <a href="%s9p0"><img src=iicons/bullbib.gif></a>
  1843. <br>
  1844. tabular format 
  1845. <a href="%s4p0"><img src=iicons/bullbib.gif></a>
  1846. <br>
  1847. Z<br>
  1848. zeroth element 
  1849. <a href="%s2p0"><img src=iicons/bullbib.gif></a>
  1850. <br>
  1851. <br>
  1852. </font>
  1853.  
  1854. </page>
  1855. </section>
  1856. <section type=Popup name=Portable title="Portability">
  1857. <page>
  1858. The (normally serious) 
  1859. effects of referencing 
  1860. elements outside the 
  1861. array bounds are 
  1862. system dependent. <br>
  1863. <br>
  1864.  
  1865. </page>
  1866. </section>
  1867. <section type=Popup name=Illustration title="Illustrations">
  1868. <page>
  1869. <a href="^Illustration::c:s0p2">Fig. 4.1</a>  A 12-element array.<br>
  1870. <a href="^Illustration::c:s0p3">Fig. 4.2</a>  Operator precedence and associativity.<br>
  1871. <a href="^Code::c:s0p0">Fig. 4.3</a>  Initializing the elements of an array to zeros.<br>
  1872. <a href="^Code::c:s0p1">Fig. 4.4</a>  Initializing the elements of an array with a declaration.<br>
  1873. <a href="^Code::c:s0p2">Fig. 4.5</a>  Generating values to be placed into elements of an array.<br>
  1874. <a href="^Code::c:s0p4">Fig. 4.6</a>  Correctly initializing and using a constant variable.<br>
  1875. <a href="^Code::c:s0p3">Fig. 4.7</a>  A const object must be initialized.<br>
  1876. <a href="^Code::c:s0p5">Fig. 4.8</a>  Computing the sum of the elements of an array.<br>
  1877. <a href="^Code::c:s0p6">Fig. 4.9</a>  A student poll analysis program.<br>
  1878. <a href="^Code::c:s0p7">Fig. 4.10</a>  A program that prints histograms.<br>
  1879. <a href="^Code::c:s0p8">Fig. 4.11</a>  Dice-rolling program using arrays instead of <b>switch</b>.<br>
  1880. <a href="^Code::c:s0p9">Fig. 4.12</a>  Treating character arrays as strings.<br>
  1881. <a href="^Code::c:s0p10">Fig. 4.13</a>  Comparing static array initialization and automatic array initialization.<br>
  1882. <a href="^Code::c:s0p11">Fig. 4.14</a>  Passing arrays and individual array elements to functions.<br>
  1883. <a href="^Code::c:s0p12">Fig. 4.15</a>  Demonstrating the <b>const</b> type qualifier.<br>
  1884. <a href="^Code::c:s0p13">Fig. 4.16</a>  Sorting an array with bubble sort.<br>
  1885. <a href="^Code::c:s0p14">Fig. 4.17</a>  Survey data analysis program.<br>
  1886. <a href="^Code::c:s0p15">Fig. 4.19</a>  Linear search of an array.<br>
  1887. <a href="^Code::c:s0p16">Fig. 4.20</a>  Binary search of a sorted array.<br>
  1888.  
  1889. </page>
  1890. <page>
  1891. <a href="^Illustration::c:s0p4">Fig. 4.21</a>  A double-subscripted array with three rows and four columns.<br>
  1892. <a href="^Code::c:s0p17">Fig. 4.22</a>  Initializing multidimensional arrays.<br>
  1893. <a href="^Code::c:s0p18">Fig. 4.23</a>  Example of using double-subscripted arrays.<br>
  1894. <a href="^Illustration::c:s0p5">Fig. 4.24</a>  The 36 possible outcomes of rolling two dice.<br>
  1895. <a href="^Illustration::c:s0p6">Fig. 4.25</a>  The eight possible moves of the knight.<br>
  1896. <a href="^Illustration::c:s0p7">Fig. 4.26</a>  The 22 squares eliminated by placing a queen in the upper-left corner.<br>
  1897. <br>
  1898.  
  1899. </page>
  1900. <page>
  1901. <font size=18><a href="~audio/Ch04/04fig001.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 4.1 - A 12-element array.<img src="graphics/ch04/fig04001.gif" ></font><br>
  1902.  
  1903. </page>
  1904. <page>
  1905. <font size=18><a href="~audio/Ch04/04fig002.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 4.2 - Operator precedence and associativity. <img src="graphics/ch04/fig04002.gif" ></font><br>
  1906.  
  1907. </page>
  1908. <page>
  1909. <font size=18>Fig<a href="~audio/Ch04/04fig021.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>ure 4.21 - A double-subscripted array with three rows and four columns.<img src="graphics/ch04/fig04021.gif" ></font><br>
  1910.  
  1911. </page>
  1912. <page>
  1913. <font size=18>Figure 4.24 - The 36 possible outcomes of rolling two dice.<img src="graphics/ch04/fig04024.gif" ></font><br>
  1914.  
  1915. </page>
  1916. <page>
  1917. <font size=18>Figure 4.25 - The eight possible moves of the knight.<img src="graphics/ch04/fig04025.gif" ></font><br>
  1918.  
  1919. </page>
  1920. <page>
  1921. <font size=18>Figure 4.26 - The 22 squares eliminated by placing a queen in the upper-left corner.</font><br>
  1922. <img src="graphics/ch04/fig04026.gif" ><br>
  1923.  
  1924. </page>
  1925. </section>
  1926. <section type=Popup name=Exercises title="Exercises">
  1927. <page pagename="Exercise 4.1">
  1928. <b>Exercise 4.1</b><br>
  1929. Answer each of the following:<br>
  1930. a)  Lists and tables of values are stored in ________.<br>
  1931. b)  The elements of an array are related by the fact that they have the same <p>
  1932. ________ and ________.<br>
  1933. c)  The number used to refer to a particular element of an array is called its <p>
  1934. ________.<br>
  1935. d)  A ________ should be used to declare the size of an array because it makes 
  1936. the program more scalable.<br>
  1937. e)  The process of placing the elements of an array in order is called ________ 
  1938. the array.<br>
  1939. <foreign  name="answers" url="^Answers::c:s0p0">
  1940.  
  1941. </page>
  1942. <page pagename="Exercise 4.1">
  1943. f)  The process of determining if an array contains a certain key value is called <p>
  1944. ________ the array.<br>
  1945. g)  An array that uses two subscripts is referred to as a ________ array.<br>
  1946. <foreign  name="answers" url="^Answers::c:s0p0">
  1947. <br>
  1948.  
  1949. </page>
  1950. <page pagename="Exercise 4.2">
  1951. <b>Exercise 4.2</b><br>
  1952. State whether the following are true or false. If the answer is false, explain why.<br>
  1953. a)  An array can store many different types of values.<br>
  1954. b)  An array subscript should normally be of data type <b>float</b>.<br>
  1955. c)  If there are fewer initializers in an initializer list than the number of elements 
  1956. in the array, the remaining elements are automatically initialized to the last value 
  1957. in the list of initializers.<br>
  1958. d)  It is an error if an initializer list contains more initializers than there are 
  1959. elements in the array.<br>
  1960. e)  An individual array element that is passed to a function and modified in that 
  1961. function will contain the modified value when the called function completes 
  1962. execution.<br>
  1963. <foreign  name="answers" url="^Answers::c:s0p1">
  1964.  
  1965. </page>
  1966. <page pagename="Exercise 4.3">
  1967. <b>Exercise 4.3</b><br>
  1968. Answer the following questions regarding an array called <b>fractions</b>.<br>
  1969. a)  Define a constant variable <b>arraySize</b> initialized to 10. <br>
  1970. b)  Declare an array with <b>arraySize</b> elements of type <b>float</b> and initialize the 
  1971. elements to <b>0</b>. <br>
  1972. c)  Name the fourth element from the beginning of the array.<br>
  1973. d)  Refer to array element 4.<br>
  1974. e)  Assign the value <b>1.667</b> to array element 9.<br>
  1975. f)  Assign the value <b>3.333</b> to the seventh element of the array.<br>
  1976. g)  Print array elements 6 and 9 with two digits of precision to the right of the 
  1977. decimal point and show the output that is actually displayed on the screen.<br>
  1978. <foreign  name="answers" url="^Answers::c:s0p2">
  1979.  
  1980. </page>
  1981. <page pagename="Exercise 4.3">
  1982. h)  Print all the elements of the array using a <b>for</b> repetition structure. Define the 
  1983. integer variable <b>x</b> as a control variable for the loop. Show the output.<br>
  1984. <foreign  name="answers" url="^Answers::c:s0p2">
  1985. <br>
  1986.  
  1987. </page>
  1988. <page pagename="Exercise 4.4">
  1989. <b>Exercise 4.4</b><br>
  1990. Answer the following questions regarding an array called <b>table</b>.<br>
  1991. a)  Declare the array to be an integer array and to have 3 rows and 3 columns. 
  1992. Assume the constant variable <b>arraySize</b> has been defined to be 3.<br>
  1993. b)  How many elements does the array contain?<br>
  1994. c)  Use a <b>for</b> repetition structure to initialize each element of the array to the sum 
  1995. of its subscripts. Assume the integer variables <b>x</b> and <b>y</b> are declared as control 
  1996. variables.<br>
  1997. d)  Write a program segment to print the values of each element of array table in 
  1998. tabular format with 3 rows and 3 columns. Assume the array was initialized with 
  1999. the declaration,<br>
  2000. <foreign  name="answers" url="^Answers::c:s0p4">
  2001.  
  2002. </page>
  2003. <page pagename="Exercise 4.4">
  2004. <font size=2><br></font><font size=11><pre>
  2005. int table[ arraySize ][ arraySize ] = <p>
  2006.    { { 1, 8 }, { 2, 4, 6 }, { 5 } };  <p>
  2007. </pre></font>
  2008. and the integer variables x and y are declared as control variables. Show the 
  2009. output.<br>
  2010. <foreign  name="answers" url="^Answers::c:s0p4">
  2011. <br>
  2012.  
  2013. </page>
  2014. <page pagename="Exercise 4.5">
  2015. <b>Exercise 4.5</b><br>
  2016. Find the error in each of the following program segments and correct the error.<br>
  2017. <font size=2><br></font><font size=11><pre>
  2018. a)  #include <iostream.h>;<p>
  2019. b)  arraySize = 10;  // arraySize was declared const<p>
  2020. </pre></font>
  2021. c)  Assume <b>int b[ 10 ] = { 0 };
  2022. </b><br>
  2023. <font size=2><br></font><font size=11><pre>
  2024. for ( int i = 0; i <= 10; i++ )<p>
  2025.    b[ i ] = 1;<p>
  2026. </pre></font>
  2027. d)  Assume <tt><b>int a[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
  2028. </b></tt><br>
  2029. <font size=2><br></font><font size=11><pre>
  2030. a[ 1, 1 ] = 5; <p>
  2031. </pre></font>
  2032. <foreign  name="answers" url="^Answers::c:s0p6">
  2033. <br>
  2034.  
  2035. </page>
  2036. <page pagename="Exercise 4.6">
  2037. <b>Exercise 4.6</b><br>
  2038. Fill in the blanks in each of the following:<br>
  2039. a)  C++ stores lists of values in ________.<br>
  2040. b)  The elements of an array are related by the fact that they ________.<br>
  2041. c)  When referring to an array element, the position number contained within 
  2042. parentheses is called a ________.<br>
  2043. d)  The names of the four elements of array <b>p</b> are _____, _____, <p>
  2044. ________, and ________.<br>
  2045. e)  Naming an array, stating its type, and specifying the number of elements in 
  2046. the array is called ________ the array.<br>
  2047. f)  The process of placing the elements of an array into either ascending or 
  2048. descending order is called ________.<br>
  2049.  
  2050. </page>
  2051. <page pagename="Exercise 4.6">
  2052. g)  In a double-subscripted array, the first subscript (by convention) identifies 
  2053. the <p>
  2054. ________ of an element, and the second subscript (by convention) identifies 
  2055. the<p>
  2056. ________ of an element.<br>
  2057. h)  An m-by-n array contains ________ rows,  ________ columns, and 
  2058. _______ elements.<br>
  2059. i)  The name of the element in row 3 and column 5 of array <b>d</b> is ________.<br>
  2060. <br>
  2061.  
  2062. </page>
  2063. <page pagename="Exercise 4.7">
  2064. <b>Exercise 4.7</b><br>
  2065. State which of the following are true and which are false; for those that are false, 
  2066. explain why they are false.<br>
  2067. a)  To refer to a particular location or element within an array, we specify the 
  2068. name of the array and the value of the particular element.<br>
  2069. b)  An array declaration reserves space for the array.<br>
  2070. c)  To indicate that 100 locations should be reserved for integer array <b>p</b>, the 
  2071. programmer writes the declaration<br>
  2072. <font size=2><br></font><font size=11><pre>
  2073. <spacer width=20 height=1><spacer width=20 height=1>p[ 100 ];<p>
  2074. </pre></font>
  2075. d)  A C++ program that initializes the elements of a 15-element array to zero 
  2076. must contain at least one <b>for</b> statement.<br>
  2077.  
  2078. </page>
  2079. <page pagename="Exercise 4.7">
  2080. e)  A C++ program that totals the elements of a double-subscripted array must 
  2081. contain nested <b>for</b> statements.<br>
  2082. <br>
  2083.  
  2084. </page>
  2085. <page pagename="Exercise 4.8">
  2086. <b>Exercise 4.8</b><br>
  2087. Write C++ statements to accomplish each of the following:<br>
  2088. a)  Display the value of the seventh element of character array <b>f</b>.<br>
  2089. b)  Input a value into element 4 of single-subscripted floating-point array <b>b</b>.<br>
  2090. c)  Initialize each of the 5 elements of single-subscripted integer array <b>g</b> to <b>8</b>. <br>
  2091. d)  Total and print the elements of floating-point array <b>c</b> of 100 elements.<br>
  2092. e)  Copy array <b>a</b> into the first portion of array <b>b</b>. Assume <b>float a[ 11 ], b[ 34 ];
  2093. </b><br>
  2094. f)  Determine and print the smallest and largest values contained in 99-element 
  2095. floating-point array <b>w</b>.<br>
  2096. <br>
  2097.  
  2098. </page>
  2099. <page pagename="Exercise 4.9">
  2100. <b>Exercise 4.9</b><br>
  2101. Consider a 2-by-3 integer array <b>t</b>.<br>
  2102. a)  Write a declaration for <b>t</b>.<br>
  2103. b)  How many rows does <b>t</b> have?<br>
  2104. c)  How many columns does <b>t </b>have?<br>
  2105. d)  How many elements does <b>t</b> have?<br>
  2106. e)  Write the names of all the elements in the second row of <b>t</b>.<br>
  2107. f)  Write the names of all the elements in the third column of <b>t</b>.<br>
  2108. g)  Write a single statement that sets the element of <b>t</b> in row 1 and column 2 to 
  2109. zero.<br>
  2110. h)  Write a series of statements that initializes each element of <b>t</b> to zero. Do not 
  2111. use a repetition structure.<br>
  2112.  
  2113. </page>
  2114. <page pagename="Exercise 4.9">
  2115. i)  Write a nested for structure that initializes each element of <b>t</b> to zero. <br>
  2116. j)  Write a statement that inputs the values for the elements of <b>t</b> from the 
  2117. terminal.<br>
  2118. k)  Write a series of statements that determines and prints the smallest value in 
  2119. array <b>t</b>.<br>
  2120. l)  Write a statement that displays the elements of the first row of <b>t</b>.<br>
  2121. m)  Write a statement that totals the elements of the fourth column of <b>t</b>.<br>
  2122. n)  Write a series of statements that prints the array <b>t</b> in neat, tabular format. List 
  2123. the column subscripts as headings across the top and list the row subscripts at 
  2124. the left of each row.<br>
  2125. <br>
  2126.  
  2127. </page>
  2128. <page pagename="Exercise 4.10">
  2129. <b>Exercise 4.10</b><br>
  2130. Use a single-subscripted array to solve the following problem. A company pays 
  2131. its salespeople on a commission basis. The salespeople receive $200 per week 
  2132. plus 9 percent of their gross sales for that week. For example, a salesperson who 
  2133. grosses $5000 in sales in a week receives $200 plus 9 percent of $5000, or a 
  2134. total of $650. Write a program (using an array of counters) that determines how 
  2135. many of the salespeople earned salaries in each of the following ranges (assume 
  2136. that each salesperson's salary is truncated to an integer amount):<br>
  2137. a)  $200-$299<br>
  2138. b)  $300-$399<br>
  2139. c)  $400-$499<br>
  2140. d)  $500-$599<br>
  2141. <foreign  name="answers" url="^Answers::c:s0p8">
  2142.  
  2143. </page>
  2144. <page pagename="Exercise 4.10">
  2145. e)  $600-$699<br>
  2146. f)  $700-$799<br>
  2147. g)  $800-$899<br>
  2148. h)  $900-$999<br>
  2149. i)  $1000 and over<br>
  2150. <foreign  name="answers" url="^Answers::c:s0p8">
  2151. <br>
  2152.  
  2153. </page>
  2154. <page pagename="Exercie 4.11">
  2155. <b>Exercie 4.11</b><br>
  2156. The bubble sort presented in <a href="^Code::c:s0p13"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.16 </a>is inefficient for large arrays. Make the 
  2157. following simple modifications to improve the performance of the bubble sort.<br>
  2158. a)  After the first pass, the largest number is guaranteed to be in the highest-
  2159. numbered element of the array; after the second pass, the two highest numbers 
  2160. are "in place," and so on. Instead of making nine comparisons on every pass, 
  2161. modify the bubble sort to make eight comparisons on the second pass, seven on 
  2162. the third pass, and so on.<br>
  2163. b)  The data in the array may already be in the proper order or near-proper order, 
  2164. so why make nine passes if fewer will suffice? Modify the sort to check at the 
  2165. end of each pass if any swaps have been made. If none has been made, then the <br>
  2166.  
  2167. </page>
  2168. <page pagename="Exercie 4.11">
  2169. data must already be in the proper order, so the program should terminate. If 
  2170. swaps have been made, then at least one more pass is needed.<br>
  2171. <br>
  2172.  
  2173. </page>
  2174. <page pagename="Exercise 4.12">
  2175. <b>Exercise 4.12</b><br>
  2176. Write single statements that perform the following single-subscripted array 
  2177. operations:<br>
  2178. a)  Initialize the 10 elements of integer array <b>counts</b> to zeros.<br>
  2179. b)  Add 1 to each of the 15 elements of integer array <b>bonus</b>.<br>
  2180. c)  Read 12 values for <b>float</b> array <b>monthlyTemperatures</b> from the keyboard.<br>
  2181. d)  Print the 5 values of integer array <b>bestScores</b> in column format.<br>
  2182. <foreign  name="answers" url="^Answers::c:s0p7">
  2183. <br>
  2184.  
  2185. </page>
  2186. <page pagename="Exercise 4.13">
  2187. <b>Exercise 4.13</b><br>
  2188. Find the error(s) in each of the following statements:<br>
  2189. a)  Assume: <b>char str[ 5 ];
  2190. </b><br>
  2191. <font size=2><br></font><font size=11><pre>
  2192. cin >> str;    // User types hello <p>
  2193. </pre></font>
  2194. b)  Assume: <b>int a[ 3 ];
  2195. </b><br>
  2196. <font size=2><br></font><font size=11><pre>
  2197. cout << a[ 1 ] << " " << a[ 2 ] << " " << a[ 3 ] << endl;<p>
  2198. float f[ 3 ] = { 1.1, 10.01, 100.001, 1000.0001 };<p>
  2199. </pre></font>
  2200. d)  Assume: <b>double d[ 2 ][ 10 ];
  2201. </b><br>
  2202. <font size=2><br></font><font size=11><pre>
  2203. d[ 1, 9 ] = 2.345;<p>
  2204. </pre></font>
  2205. <br>
  2206.  
  2207. </page>
  2208. <page pagename="Exercise 4.14">
  2209. <b>Exercise 4.14</b><br>
  2210. Modify the program of <a href="^Code::c:s0p14"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.17</a> so function <b>mode</b> is capable of handling a tie 
  2211. for the mode value. Also modify function <b>median</b> so the two middle elements 
  2212. are averaged in an array with an even number of elements.<br>
  2213. <br>
  2214.  
  2215. </page>
  2216. <page pagename="Exercise 4.15">
  2217. <b>Exercise 4.15</b><br>
  2218. Use a single-subscripted array to solve the following problem. Read in 20 
  2219. numbers, each of which is between 10 and 100, inclusive. As each number is 
  2220. read, print it only if it is not a duplicate of a number already read. Provide for the 
  2221. "worst case" in which all 20 numbers are different. Use the smallest possible 
  2222. array to solve this problem.<br>
  2223. <foreign  name="answers" url="^Answers::c:s0p9">
  2224. <br>
  2225.  
  2226. </page>
  2227. <page pagename="Exercise 4.16">
  2228. <b>Exercise 4.16</b><br>
  2229. Label the elements of 3-by-5 double-subscripted array <b>sales</b> to indicate the order 
  2230. in which they are set to zero by the following program segment:<br>
  2231. <font size=2><br></font><font size=11><pre>
  2232. for ( row = 0; row < 3; row++ ) <p>
  2233.    for ( column = 0; column < 5; column++ )<p>
  2234.       sales[ row ][ column ] = 0;<p>
  2235. </pre></font>
  2236. <br>
  2237.  
  2238. </page>
  2239. <page pagename="Exercise 4.17">
  2240. <b>Exercise 4.17</b><br>
  2241. Write a program that simulates the rolling of two dice. The program should use 
  2242. <b>rand</b> to roll the first die, and should use rand again to roll the second die. The 
  2243. sum of the two values should then be calculated. <i>Note:</i> Since each die can show 
  2244. an integer value from 1 to 6, then the sum of the two values will vary from 2 to 
  2245. 12 with 7 being the most frequent sum and 2 and 12 being the least frequent 
  2246. sums. <a href="^Illustration::c:s0p5"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 4.24</a> shows the 36 possible combinations of the two dice. Your 
  2247. program should roll the two dice 36,000 times. Use a single-subscripted array to 
  2248. tally the numbers of times each possible sum appears. Print the results in a 
  2249. tabular format. Also, determine if the totals are reasonable, i.e., there are six 
  2250. ways to roll a 7, so approximately one sixth of all the rolls should be 7.<br>
  2251. <br>
  2252.  
  2253. </page>
  2254. <page pagename="Exercise 4.18">
  2255. <b>Exercise 4.18</b><br>
  2256. What does the following program do?<br>
  2257.  
  2258. <font size=14><pre>
  2259.  1 // ex04_18.cpp<p>
  2260.  2 #include <iostream.h><p>
  2261.  3 <p>
  2262.  4 int whatIsThis( int [], int );<p>
  2263.  5 <p>
  2264.  6 int main()<p>
  2265.  7 {<p>
  2266.  8    const int arraySize = 10;<p>
  2267.  9    int a[ arraySize ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };<p>
  2268.  10 <p>
  2269.  11    int result = whatIsThis( a, arraySize );<p>
  2270.  12 <p>
  2271. </pre></font>
  2272.  
  2273. </page>
  2274. <page pagename="Exercise 4.18">
  2275. <font size=14><pre>
  2276.  13    cout << "Result is " << result << endl;<p>
  2277. </pre></font>
  2278. <font size=14><pre>
  2279.  14    return 0;<p>
  2280.  15 }<p>
  2281.  16 <p>
  2282.  17 int whatIsThis( int b[], int size )<p>
  2283.  18 {<p>
  2284.  19    if ( size == 1 )<p>
  2285.  20       return b[ 0 ];<p>
  2286.  21    else<p>
  2287.  22       return b[ size - 1 ] + whatIsThis( b, size - 1 );<p>
  2288.  23 }<p>
  2289. </pre></font>
  2290. <br>
  2291.  
  2292. </page>
  2293. <page pagename="Exercise 4.19">
  2294. <b>Exercise 4.19</b><br>
  2295. Write a program that runs 1000 games of craps and answers the following 
  2296. questions:<br>
  2297. a)  How many games are won on the first roll, second roll, \xc9 , twentieth roll, and 
  2298. after the twentieth roll?<br>
  2299. b)  How many games are lost on the first roll, second roll, \xc9 , twentieth roll, and 
  2300. after the twentieth roll? <br>
  2301. c)  What are the chances of winning at craps? (<i>Note:</i> You should discover that 
  2302. craps is one of the fairest casino games. What do you suppose this means?)<br>
  2303. d)  What is the average length of a game of craps?<br>
  2304. e)  Do the chances of winning improve with the length of the game?<br>
  2305. <br>
  2306.  
  2307. </page>
  2308. <page pagename="Exercise 4.20">
  2309. <b>Exercise 4.20</b><br>
  2310. (<i>Airline Reservations System</i>) A small airline has just purchased a computer for 
  2311. its new automated reservations system. You have been asked to program the new 
  2312. system. You are to write a program to assign seats on each flight of the airline's 
  2313. only plane (capacity: 10 seats).<br>
  2314. <spacer width=20 height=1>Your program should display the following menu of alternatives--<b>Please type 1 
  2315. for "smoking" and Please type 2 for "nonsmoking"</b>. If the person types 1, 
  2316. your program should assign a seat in the smoking section (seats 1-5). If the 
  2317. person types 2, your program should assign a seat in the nonsmoking section 
  2318. (seats 6-10). Your program should print a boarding pass indicating the person's 
  2319. seat number and whether it is in the smoking or nonsmoking section of the 
  2320. plane.<br>
  2321. <foreign  name="answers" url="^Answers::c:s0p10">
  2322.  
  2323. </page>
  2324. <page pagename="Exercise 4.20">
  2325. <spacer width=20 height=1>Use a single-subscripted array to represent the seating chart of the plane. 
  2326. Initialize all the elements of the array to 0 to indicate that all seats are empty. As 
  2327. each seat is assigned, set the corresponding elements of the array to 1 to indicate 
  2328. that the seat is no longer available.<br>
  2329. <spacer width=20 height=1>Your program should, of course, never assign a seat that has already been 
  2330. assigned. When the smoking section is full, your program should ask the person 
  2331. if it is acceptable to be placed in the nonsmoking section (and vice versa). If yes, 
  2332. then make the appropriate seat assignment. If no, then print the message <b>"Next 
  2333. flight leaves in 3 hours."
  2334. </b><br>
  2335. <foreign  name="answers" url="^Answers::c:s0p10">
  2336. <br>
  2337.  
  2338. </page>
  2339. <page pagename="Exercise 4.21">
  2340. <b>Exercise 4.21</b><br>
  2341. What does the following program do?<br>
  2342.  
  2343. <font size=14><pre>
  2344.  1 // ex04_21.cpp<p>
  2345.  2 #include <iostream.h><p>
  2346.  3 <p>
  2347.  4 void someFunction( int [], int );<p>
  2348.  5 <p>
  2349.  6 int main()<p>
  2350.  7 {<p>
  2351.  8    const int arraySize = 10;<p>
  2352.  9    int a[ arraySize ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };<p>
  2353.  10 <p>
  2354.  11    cout << "The values in the array are:" << endl;<p>
  2355. </pre></font>
  2356.  
  2357. </page>
  2358. <page pagename="Exercise 4.21">
  2359. <font size=14><pre>
  2360.  12    someFunction( a, arraySize );<p>
  2361. </pre></font>
  2362. <font size=14><pre>
  2363.  13    cout << endl;<p>
  2364.  14    return 0;<p>
  2365.  15 }<p>
  2366.  16 <p>
  2367.  17 void someFunction( int b[], int size )<p>
  2368.  18 {<p>
  2369.  19    if ( size > 0 ) {<p>
  2370.  20       someFunction( &b[ 1 ], size - 1 );<p>
  2371.  21       cout << b[ 0 ] << "  ";<p>
  2372.  22    }<p>
  2373.  23 }<p>
  2374. </pre></font>
  2375. <br>
  2376.  
  2377. </page>
  2378. <page pagename="Exercise 4.22">
  2379. <b>Exercise 4.22</b><br>
  2380. Use a double-subscripted array to solve the following problem. A company has 
  2381. four salespeople (1 to 4) who sell five different products (1 to 5). Once a day, 
  2382. each salesperson passes in a slip for each different type of product sold. Each 
  2383. slip contains:<br>
  2384. a)  The salesperson number<br>
  2385. b)  The product number<br>
  2386. c)  The total dollar value of that product sold that day<br>
  2387. Thus, each salesperson passes in between 0 and 5 sales slips per day. Assume 
  2388. that the information from all of the slips for last month is available. Write a 
  2389. program that will read all this information for last month's sales, and summarize 
  2390. the total sales by salesperson by product. All totals should be stored in the <br>
  2391.  
  2392. </page>
  2393. <page pagename="Exercise 4.22">
  2394. double-subscripted array <b>sales</b>. After processing all the information for last 
  2395. month, print the results in tabular format with each of the columns representing a 
  2396. particular salesperson and each of the rows representing a particular product. 
  2397. Cross total each row to get the total sales of each product for last month; cross 
  2398. total each column to get the total sales by salesperson for last month. Your 
  2399. tabular printout should include these cross totals to the right of the totaled rows 
  2400. and to the bottom of the totaled columns.<br>
  2401. <br>
  2402.  
  2403. </page>
  2404. <page pagename="Exercise 4.23">
  2405. <b>Exercise 4.23</b><br>
  2406. (<i>Turtle Graphics</i>) The Logo language, which is particularly popular among 
  2407. personal computer users, made the concept of <i>turtle graphics</i> famous. Imagine a 
  2408. mechanical turtle that walks around the room under the control of a C++ 
  2409. program. The turtle holds a pen in one of two positions, up or down. While the 
  2410. pen is down, the turtle traces out shapes as it moves; while the pen is up, the 
  2411. turtle moves about freely without writing anything. In this problem you will 
  2412. simulate the operation of the turtle and create a computerized sketchpad as well. <br>
  2413. <spacer width=20 height=1>Use a 20-by-20 array <b>floor</b> which is initialized to zeros. Read commands from 
  2414. an array that contains them. Keep track of the current position of the turtle at all 
  2415. times and whether the pen is currently up or down. Assume that the turtle always<br>
  2416. <foreign  name="answers" url="^Answers::c:s0p11">
  2417.  
  2418. </page>
  2419. <page pagename="Exercise 4.23">
  2420. starts at position 0,0 of the floor with its pen up. The set of turtle commands your 
  2421. program must process are as follows: <img src="graphics/ch04/ex04023.gif" ><br>
  2422. <foreign  name="answers" url="^Answers::c:s0p11">
  2423.  
  2424. </page>
  2425. <page pagename="Exercise 4.23">
  2426. Suppose that the turtle is somewhere near the center of the floor. The following 
  2427. "program" would draw and print a 12-by 12-square leaving the pen in the up 
  2428. position:<br>
  2429. <foreign  name="answers" url="^Answers::c:s0p11">
  2430.  
  2431. </page>
  2432. <page pagename="Exercise 4.23">
  2433. 6<p>
  2434. 9<br>
  2435. As the turtle moves with the pen down, set the appropriate elements of array 
  2436. <b>floor</b> to <b>1</b>s. When the <b>6</b> command (print) is given, wherever there is a <b>1</b> in the 
  2437. array, display an asterisk, or some other character you choose. Wherever there is 
  2438. a zero display a blank. Write a program to implement the turtle graphics 
  2439. capabilities discussed here. Write several turtle graphics programs to draw 
  2440. interesting shapes. Add other commands to increase the power of your turtle 
  2441. graphics language.<br>
  2442. <foreign  name="answers" url="^Answers::c:s0p11">
  2443. <br>
  2444.  
  2445. </page>
  2446. <page pagename="Exercise 4.24">
  2447. <b>Exercise 4.24</b><br>
  2448. (<i>Knight's Tour</i>) One of the more interesting puzzlers for chess buffs is the 
  2449. Knight's Tour problem, originally proposed by the mathematician Euler. The 
  2450. question is this: Can the chess piece called the knight move around an empty 
  2451. chessboard and touch each of the 64 squares once and only once? We study this 
  2452. intriguing problem in depth here.<br>
  2453. <spacer width=20 height=1>The knight makes L-shaped moves (over two in one direction and then over one 
  2454. in a perpendicular direction). Thus, from a square in the middle of an empty 
  2455. chessboard, the knight can make eight different moves (numbered 0 through 7) 
  2456. as shown in  <a href="^Illustration::c:s0p6"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.25</a>.<br>
  2457. a)  Draw an 8-by-8 chessboard on a sheet of paper and attempt a Knight's Tour 
  2458. by hand. Put a <b>1</b> in the first square you move to, a <b>2</b> in the second square, a <b>3</b> in <br>
  2459.  
  2460. </page>
  2461. <page pagename="Exercise 4.24">
  2462. the third, etc. Before starting the tour, estimate how far you think you will get, 
  2463. remembering that a full tour consists of 64 moves. How far did you get? Was 
  2464. this close to your estimate?<br>
  2465. b)  Now let us develop a program that will move the knight around a chessboard. 
  2466. The board is represented by an 8-by-8 double-subscripted array <b>board</b>. Each of 
  2467. the squares is initialized to zero. We describe each of the eight possible moves in 
  2468. terms of both their horizontal and vertical components. For example, a move of 
  2469. type 0 as shown in <a href="^Illustration::c:s0p6"> <img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.25</a> consists of moving two squares horizontally to the 
  2470. right and one square vertically upward. Move 2 consists of moving one square 
  2471. horizontally to the left and two squares vertically upward. Horizontal moves to 
  2472. the left and vertical moves upward are indicated with negative numbers. The <br>
  2473.  
  2474. </page>
  2475. <page pagename="Exercise 4.24">
  2476. eight moves may be described by two single-subscripted arrays, <b>horizontal</b> and 
  2477. <b>vertical</b>, as follows:<br>
  2478. <font size=2><br></font><font size=11><pre>
  2479. horizontal[ 0 ] = 2<p>
  2480. horizontal[ 1 ] = 1<p>
  2481. horizontal[ 2 ] = -1<p>
  2482. horizontal[ 3 ] = -2<p>
  2483. horizontal[ 4 ] = -2<p>
  2484. horizontal[ 5 ] = -1<p>
  2485. horizontal[ 6 ] = 1<p>
  2486. horizontal[ 7 ] = 2<p>
  2487. <p>
  2488. vertical[ 0 ] = -1<p>
  2489. vertical[ 1 ] = -2<p>
  2490. vertical[ 2 ] = -2<p>
  2491. vertical[ 3 ] = -1<p>
  2492. vertical[ 4 ] = 1<p><p>
  2493. </pre></font>
  2494.  
  2495. </page>
  2496. <page pagename="Exercise 4.24">
  2497. <font size=2><br></font><font size=11><pre>
  2498. vertical[ 5 ] = 2<p>
  2499. vertical[ 6 ] = 2<p>
  2500. vertical[ 7 ] = 1<p>
  2501. </pre></font>
  2502. Let the variables <b>currentRow </b>and <b>currentColumn</b> indicate the row and column 
  2503. of the knight's current position. To make a move of type <b>moveNumber</b>, where 
  2504. <b>moveNumber</b> is between 0 and 7, your program uses the statements<br>
  2505. <font size=2><br></font><font size=11><pre>
  2506. currentRow += vertical[ moveNumber ];<p>
  2507. currentColumn += horizontal[ moveNumber ];<p>
  2508. </pre></font>
  2509. Keep a counter that varies from <b>1</b> to <b>64</b>. Record the latest count in each square 
  2510. the knight moves to. Remember to test each potential move to see if the knight 
  2511. has already visited that square. And, of course, test every potential move to 
  2512. make sure that the knight does not land off the chessboard. Now write a program <br>
  2513.  
  2514. </page>
  2515. <page pagename="Exercise 4.24">
  2516. to move the knight around the chessboard. Run the program. How many moves 
  2517. did the knight make?<br>
  2518. c)  After attempting to write and run a Knight's Tour program, you have 
  2519. probably developed some valuable insights. We will use these to develop a 
  2520. <i>heuristic</i> (or strategy) for moving the knight. Heuristics do not guarantee 
  2521. success, but a carefully developed heuristic greatly improves the chance of 
  2522. success. You may have observed that the outer squares are more troublesome 
  2523. than the squares nearer the center of the board. In fact, the most troublesome, or 
  2524. inaccessible, squares are the four corners.<br>
  2525. Intuition may suggest that you should attempt to move the knight to the most 
  2526. troublesome squares first and leave open those that are easiest to get to so when <br>
  2527.  
  2528. </page>
  2529. <page pagename="Exercise 4.24">
  2530. the board gets congested near the end of the tour there will be a greater chance of 
  2531. success.<br>
  2532. We may develop an "accessibility heuristic" by classifying each of the squares 
  2533. according to how accessible they are, and then always moving the knight to the 
  2534. square (within the knight's L-shaped moves, of course) that is most inaccessible. 
  2535. We label a double-subscripted array <b>accessibility</b> with numbers indicating from 
  2536. how many squares each particular square is accessible. On a blank chessboard, 
  2537. each center square is rated as <b>8</b>, each corner square is rated as <b>2</b>, and the other 
  2538. squares have accessibility numbers of <b>3</b>, <b>4</b>, or <b>6</b> as follows:<br>
  2539.  
  2540. </page>
  2541. <page pagename="Exercise 4.24">
  2542. <font size=2><br></font><font size=11><pre>
  2543. <b>2  3  4  4  4  4  3  2<p>
  2544. 3  4  6  6  6  6  4  3<p>
  2545. 4  6  8  8  8  8  6  4<p>
  2546. 4  6  8  8  8  8  6  4<p>
  2547. 4  6  8  8  8  8  6  4<p>
  2548. 4  6  8  8  8  8  6  4<p>
  2549. 3  4  6  6  6  6  4  3<p>
  2550. 2  3  4  4  4  4  3  2
  2551. </b><p>
  2552. </pre></font>
  2553. Now write a version of the Knight's Tour program using the accessibility 
  2554. heuristic. At any time, the knight should move to the square with the lowest 
  2555. accessibility number. In case of a tie, the knight may move to any of the tied 
  2556. squares. Therefore, the tour may begin in any of the four corners. (<i>Note:</i> As the 
  2557. knight moves around the chessboard, your program should reduce the <br>
  2558.  
  2559. </page>
  2560. <page pagename="Exercise 4.24">
  2561. accessibility numbers as more and more squares become occupied. In this way, 
  2562. at any given time during the tour, each available square's accessibility number 
  2563. will remain equal to precisely the number of squares from which that square 
  2564. may be reached.) Run this version of your program. Did you get a full tour? 
  2565. Now modify the program to run 64 tours, one starting from each square of the 
  2566. chessboard. How many full tours did you get?<br>
  2567. d)  Write a version of the Knight's Tour program which, when encountering a tie 
  2568. between two or more squares, decides what square to choose by looking ahead 
  2569. to those squares reachable from the "tied" squares. Your program should move 
  2570. to the square for which the next move would arrive at a square with the lowest 
  2571. accessibility number.<br>
  2572. <br>
  2573.  
  2574. </page>
  2575. <page pagename="Exercise 4.25">
  2576. <b>Exercise 4.25</b><br>
  2577. (<i>Knight's Tour: Brute Force Approaches</i>) In <a href="^Exercises::c:s0p38"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.24</a> we developed a 
  2578. solution to the Knight's Tour problem. The approach used, called the 
  2579. "accessibility heuristic," generates many solutions and executes efficiently.<br>
  2580. <spacer width=20 height=1>As computers continue increasing in power, we will be able to solve more 
  2581. problems with sheer computer power and relatively unsophisticated algorithms. 
  2582. Let us call this approach "brute force" problem solving.<br>
  2583. a)  Use random number generation to enable the knight to walk around the chess 
  2584. board (in its legitimate L-shaped moves, of course) at random. Your program 
  2585. should run one tour and print the final chessboard. How far did the knight get?<br>
  2586. b)  Most likely, the preceding program produced a relatively short tour. Now 
  2587. modify your program to attempt 1000 tours. Use a single-subscripted array to <br>
  2588.  
  2589. </page>
  2590. <page pagename="Exercise 4.25">
  2591. keep track of the number of tours of each length. When your program finishes 
  2592. attempting the 1000 tours, it should print this information in neat tabular format. 
  2593. What was the best result?<br>
  2594. c)  Most likely, the preceding program gave you some "respectable" tours but no 
  2595. full tours. Now "pull all the stops out" and simply let your program run until it 
  2596. produces a full tour. (<i>Caution:</i> This version of the program could run for hours 
  2597. on a powerful computer.) Once again, keep a table of the number of tours of 
  2598. each length, and print this table when the first full tour is found. How many tours 
  2599. did your program attempt before producing a full tour? How much time did it 
  2600. take?<br>
  2601. d)  Compare the brute force version of the Knight's Tour with the accessibility 
  2602. heuristic version. Which required a more careful study of the problem? Which <br>
  2603.  
  2604. </page>
  2605. <page pagename="Exercise 4.25">
  2606. algorithm was more difficult to develop? Which required more computer power? 
  2607. Could we be certain (in advance) of obtaining a full tour with the accessibility 
  2608. heuristic approach? Could we be certain (in advance) of obtaining a full tour 
  2609. with the brute force approach? Argue the pros and cons of brute force problem 
  2610. solving in general.<br>
  2611. <br>
  2612.  
  2613. </page>
  2614. <page pagename="Exercise 4.26">
  2615. <b>Exercise 4.26</b><br>
  2616. (<i>Eight Queens</i>) Another puzzler for chess buffs is the Eight Queens problem. 
  2617. Simply stated: Is it possible to place eight queens on an empty chessboard so 
  2618. that no queen is "attacking" any other, i.e., no two queens are in the same row, 
  2619. the same column, or along the same diagonal? Use the thinking developed in  
  2620. <a href="^Exercises::c:s0p38"><img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.24</a> to formulate a heuristic for solving the Eight Queens problem. 
  2621. Run your program. (<i>Hint:</i> It is possible to assign a value to each square of the 
  2622. chessboard indicating how many squares of an empty chessboard are 
  2623. "eliminated" if a queen is placed in that square. Each of the corners would be 
  2624. assigned the value 22, as in  <a href="^Illustration::c:s0p7"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 4.26</a>.) Once these "elimination numbers" are 
  2625. placed in all 64 squares, an appropriate heuristic might be: Place the next queen <br>
  2626.  
  2627. </page>
  2628. <page pagename="Exercise 4.26">
  2629. in the square with the smallest elimination number. Why is this strategy 
  2630. intuitively appealing?<br>
  2631. <br>
  2632.  
  2633. </page>
  2634. <page pagename="Exercise 4.27">
  2635. <b>Exercise 4.27</b><br>
  2636. (<i>Eight Queens: Brute Force Approaches</i>) In this exercise you will develop 
  2637. several brute force approaches to solving the Eight Queens problem introduced 
  2638. in  <a href="^Exercises::c:s0p49"><img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.26</a>.<br>
  2639. a)  Solve the Eight Queens exercise, using the random brute force technique 
  2640. developed in <a href="^Exercises::c:s0p46"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.25</a>.<br>
  2641. b)  Use an exhaustive technique, i.e., try all possible combinations of eight 
  2642. queens on the chessboard.<br>
  2643. c)  Why do you suppose the exhaustive brute force approach may not be 
  2644. appropriate for solving the Knight's Tour problem?<br>
  2645. d)  Compare and contrast the random brute force and exhaustive brute force 
  2646. approaches in general.<br>
  2647.  
  2648. </page>
  2649. <page pagename="Exercise 4.28">
  2650. <b>Exercise 4.28</b><br>
  2651. (<i>Knight's Tour: Closed Tour Test</i>) In the Knight's Tour, a full tour occurs when 
  2652. the knight makes 64 moves touching each square of the chess board once and 
  2653. only once. A closed tour occurs when the 64th move is one move away from the 
  2654. location in which the knight started the tour. Modify the Knight's Tour program 
  2655. you wrote in <a href="^Exercises::c:s0p38"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.24</a> to test for a closed tour if a full tour has occurred.<br>
  2656. <br>
  2657.  
  2658. </page>
  2659. <page pagename="Exercise 4.29">
  2660. <b>Exercise 4.29</b><br>
  2661. (<i>The Sieve of Eratosthenes</i>) A prime integer is any integer that is evenly 
  2662. divisible only by itself and 1. The Sieve of Eratosthenes is a method of finding 
  2663. prime numbers. It operates as follows:<br>
  2664. a)  Create an array with all elements initialized to 1 (true). Array elements with 
  2665. prime subscripts will remain 1. All other array elements will eventually be set to 
  2666. zero.<br>
  2667. b)  Starting with array subscript 2 (subscript 1 must be prime), every time an 
  2668. array element is found whose value is 1, loop through the remainder of the array 
  2669. and set to zero every element whose subscript is a multiple of the subscript for 
  2670. the element with value 1. For array subscript 2, all elements beyond 2 in the 
  2671. array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.); for<br>
  2672. <foreign  name="answers" url="^Answers::c:s0p12">
  2673.  
  2674. </page>
  2675. <page pagename="Exercise 4.29">
  2676. array subscript 3, all elements beyond 3 in the array that are multiples of 3 will 
  2677. be set to zero (subscripts 6, 9, 12, 15, etc.); and so on.<br>
  2678. When this process is complete, the array elements that are still set to one indicate 
  2679. that the subscript is a prime number. These subscripts can then be printed. Write 
  2680. a program that uses an array of 1000 elements to determine and print the prime 
  2681. numbers between 1 and 999. Ignore element 0 of the array.<br>
  2682. <foreign  name="answers" url="^Answers::c:s0p12">
  2683. <br>
  2684.  
  2685. </page>
  2686. <page pagename="Exercise 4.30">
  2687. <b>Exercise 4.30</b><br>
  2688. (<i>Bucket Sort</i>) A bucket sort begins with a single-subscripted array of positive 
  2689. integers to be sorted, and a double-subscripted array of integers with rows 
  2690. subscripted from 0 to 9 and columns subscripted from 0 to n - 1 where n is the 
  2691. number of values in the array to be sorted. Each row of the double-subscripted 
  2692. array is referred to as a bucket. Write a function <b>bucketSort</b> that takes an integer 
  2693. array and the array size as arguments and performs as follows:<br>
  2694. a)  Place each value of the single-subscripted array into a row of the bucket array 
  2695. based on the value's ones digit. For example, 97 is placed in row 7, 3 is placed in 
  2696. row 3, and 100 is placed in row 0. This is called a "distribution pass."<br>
  2697. <foreign  name="answers" url="^Answers::c:s0p13">
  2698.  
  2699. </page>
  2700. <page pagename="Exercise 4.30">
  2701. b)  Loop through the bucket array row-by-row and copy the values back to the 
  2702. original array. This is called a "gathering pass." The new order of the preceding 
  2703. values in the single-subscripted array is 100, 3, and 97.<br>
  2704. c)  Repeat this process for each subsequent digit position (tens, hundreds, 
  2705. thousands, etc.). <br>
  2706. On the second pass, 100 is placed in row 0, 3 is placed in row 0 (because 3 has 
  2707. no tens digit), and 97 is placed in row 9. After the gathering pass, the order of 
  2708. the values in the single-subscripted array is 100, 3, and 97. On the third pass, 
  2709. 100 is placed in row 1, 3 is placed in row zero and 97 is placed in row zero (after 
  2710. the 3). After the last gathering pass, the original array is now in sorted order. <br>
  2711. <spacer width=20 height=1>Note that the double-subscripted array of buckets is ten times the size of the 
  2712. integer array being sorted. This sorting technique provides better performance<br>
  2713. <foreign  name="answers" url="^Answers::c:s0p13">
  2714.  
  2715. </page>
  2716. <page pagename="Exercise 4.30">
  2717. than a bubble sort, but requires much more memory. The bubble sort requires 
  2718. space for only one additional element of data. This is an example of the space-
  2719. time tradeoff: The bucket sort uses more memory than the bubble sort, but 
  2720. performs better. This version of the bucket sort requires copying all the data 
  2721. back to the original array on each pass. Another possibility is to create a second 
  2722. double-subscripted bucket array and repeatedly swap the data between the two 
  2723. bucket arrays.<br>
  2724. <foreign  name="answers" url="^Answers::c:s0p13">
  2725. <br>
  2726.  
  2727. </page>
  2728. <page pagename="Recursion Exercises">
  2729. <b>Recursion Exercises</b><br>
  2730.  
  2731. </page>
  2732. <page pagename="Exercise 4.31">
  2733. <b>Exercise 4.31</b><br>
  2734. (<i>Selection Sort</i>) A selection sort searches an array looking for the smallest 
  2735. element in the array. Then, the smallest element is swapped with the first 
  2736. element of the array. The process is repeated for the subarray beginning with the 
  2737. second element of the array. Each pass of the array results in one element being 
  2738. placed in its proper location. This sort performs comparably to the bubble sort--
  2739. for an array of <i>n</i> elements, <i>n - 1</i> passes must be made, and for each subarray, <i>n - 
  2740. 1</i> comparisons must be made to find the smallest value. When the subarray being 
  2741. processed contains one element, the array is sorted. Write recursive function 
  2742. <b>selectionSort</b> to perform this algorithm.<br>
  2743. <br>
  2744.  
  2745. </page>
  2746. <page pagename="Exercise 4.32">
  2747. <b>Exercise 4.32</b><br>
  2748. (<i>Palindromes</i>) A palindrome is a string that is spelled the same way forwards 
  2749. and backwards. Some examples of palindromes are: "radar," "able was i ere i 
  2750. saw elba," and (if blanks are ignored) "a man a plan a canal panama." Write a 
  2751. recursive function <b>testPalindrome</b> that returns <b>true</b> if the string stored in the 
  2752. array is a palindrome, and <b>false</b> otherwise. The function should ignore spaces 
  2753. and punctuation in the string. <br>
  2754. <br>
  2755.  
  2756. </page>
  2757. <page pagename="Exercise 4.33">
  2758. <b>Exercise 4.33</b><br>
  2759. (<i>Linear Search)</i> Modify  <a href="^Code::c:s0p15"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.19</a> to use recursive function <b>linearSearch</b> to 
  2760. perform a linear search of the array. The function should receive an integer array 
  2761. and the size of the array as arguments. If the search key is found, return the array 
  2762. subscript; otherwise, return 1.<br>
  2763. <foreign  name="answers" url="^Answers::c:s0p14">
  2764. <br>
  2765.  
  2766. </page>
  2767. <page pagename="Exercise 4.34">
  2768. <b>Exercise 4.34</b><br>
  2769. (<i>Binary Search</i>) Modify the program of  <a href="^Code::c:s0p16"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 4.20</a> to use a recursive function 
  2770. <b>binarySearch</b> to perform the binary search of the array. The function should 
  2771. receive an integer array and the starting subscript and ending subscript as 
  2772. arguments. If the search key is found, return the array subscript; otherwise, 
  2773. return 1.<br>
  2774. <br>
  2775.  
  2776. </page>
  2777. <page pagename="Exercise 4.35">
  2778. <b>Exercise 4.35</b><br>
  2779. (<i>Eight Queens</i>) Modify the Eight Queens program you created in  <a href="^Exercises::c:s0p49"> <img src="bckgrnds/icons/exercise.gif" align=sidebar>Exercise 4.26</a> 
  2780. to solve the problem recursively. <br>
  2781. <br>
  2782.  
  2783. </page>
  2784. <page pagename="Exercise 4.36">
  2785. <b>Exercise 4.36</b><br>
  2786. (<i>Print an array</i>) Write a recursive function <b>printArray</b> that takes an array and 
  2787. the size of the array as arguments and returns nothing. The function should stop 
  2788. processing and return when it receives an array of size zero.<br>
  2789. <foreign  name="answers" url="^Answers::c:s0p15">
  2790. <br>
  2791.  
  2792. </page>
  2793. <page pagename="Exercise 4.37">
  2794. <b>Exercise 4.37</b><br>
  2795. (<i>Print a string backwards</i>) Write a recursive function <b>stringReverse </b>that takes a 
  2796. character array containing a string as an argument, prints the string backwards, 
  2797. and returns nothing. The function should stop processing and return when the 
  2798. terminating null character is encountered.<br>
  2799. <br>
  2800.  
  2801. </page>
  2802. <page pagename="Exercise 4.38">
  2803. <b>Exercise 4.38</b><br>
  2804. (<i>Find the minimum value in an array</i>) Write a recursive function 
  2805. <b>recursiveMinimum</b> that takes an integer array and the array size as arguments 
  2806. and returns the smallest element of the array. The function should stop 
  2807. processing and return when it receives an array of 1 element.<br>
  2808. <foreign  name="answers" url="^Answers::c:s0p16">
  2809. <br>
  2810.  
  2811. </page>
  2812. </section>
  2813. <section type=Popup name=Objective title="Objectives">
  2814. <page>
  2815. <indent width=8 delay>*   To introduce the array data structure.</indent>
  2816. <indent width=8 delay>*   To understand the use of arrays to store, sort, and search lists and tables of 
  2817. values. </indent>
  2818. <indent width=8 delay>*   To understand how to declare an array, initialize an array, and refer to 
  2819. individual elements of an array.</indent>
  2820. <foreign  name="audio" url="~audio/Ch04/04obj.au">
  2821.  
  2822. </page>
  2823. <page>
  2824. <indent width=8 delay>*   To be able to pass arrays to functions.</indent>
  2825. <indent width=8 delay>*   To understand basic sorting techniques.</indent>
  2826. <indent width=8 delay>*   To be able to declare and manipulate multiple-subscript arrays.</indent>
  2827.  
  2828. </page>
  2829. </section>
  2830. <section type=Popup name=Code title="Code Examples">
  2831. <page>
  2832. <font size=18>Figure 4.3  Initializing the elements of an array to zeros.</font><br>
  2833. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2834. <param  name="file" value="code/ch04/fig04_03.txt">
  2835. </applet><br>
  2836. <br>
  2837. <foreign  name="copy2disk" url="!jcpy Source/fig04_03.jar">
  2838. <foreign  name="audio" url="~audio/Ch04/04fig003.au">
  2839. <foreign  name="execute" url="!jarexe Run/fig04_03.jar">
  2840. <br>
  2841.  
  2842. </page>
  2843. <page>
  2844. <font size=18>Figure 4.4  Initializing the elements of an array with a declaration.</font><br>
  2845. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2846. <param  name="file" value="code/ch04/fig04_04.txt">
  2847. </applet><br>
  2848. <br>
  2849. <foreign  name="copy2disk" url="!jcpy Source/fig04_04.jar">
  2850. <foreign  name="audio" url="~audio/Ch04/04fig004.au">
  2851. <foreign  name="execute" url="!jarexe Run/fig04_04.jar">
  2852. <br>
  2853.  
  2854. </page>
  2855. <page>
  2856. <font size=18>Figure 4.5  Generating values to be placed into elements of an array.</font><br>
  2857. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2858. <param  name="file" value="code/ch04/fig04_05.txt">
  2859. </applet><br>
  2860. <br>
  2861. <foreign  name="copy2disk" url="!jcpy Source/fig04_05.jar">
  2862. <foreign  name="audio" url="~audio/Ch04/04fig005.au">
  2863. <foreign  name="execute" url="!jarexe Run/fig04_05.jar">
  2864. <br>
  2865.  
  2866. </page>
  2867. <page>
  2868. <font size=18>Figure 4.7  A const object must be initialized.</font><br>
  2869. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2870. <param  name="file" value="code/ch04/fig04_07.txt">
  2871. </applet><br>
  2872. <br>
  2873. <foreign  name="copy2disk" url="!jcpy Source/fig04_07.jar">
  2874. <foreign  name="audio" url="~audio/Ch04/04fig007.au">
  2875. <br>
  2876.  
  2877. </page>
  2878. <page>
  2879. <font size=18>Figure 4.6  Correctly initializing and using a constant variable.</font><br>
  2880. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2881. <param  name="file" value="code/ch04/fig04_06.txt">
  2882. </applet><br>
  2883. <br>
  2884. <foreign  name="copy2disk" url="!jcpy Source/fig04_06.jar">
  2885. <foreign  name="audio" url="~audio/Ch04/04fig006.au">
  2886. <foreign  name="execute" url="!jarexe Run/fig04_06.jar">
  2887. <br>
  2888.  
  2889. </page>
  2890. <page>
  2891. <font size=18>Figure 4.8  Computing the sum of the elements of an array.</font><br>
  2892. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2893. <param  name="file" value="code/ch04/fig04_08.txt">
  2894. </applet><br>
  2895. <br>
  2896. <foreign  name="copy2disk" url="!jcpy Source/fig04_08.jar">
  2897. <foreign  name="audio" url="~audio/Ch04/04fig008.au">
  2898. <foreign  name="execute" url="!jarexe Run/fig04_08.jar">
  2899. <br>
  2900.  
  2901. </page>
  2902. <page>
  2903. <font size=18>Figure 4.9  A student poll analysis program.</font><br>
  2904. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2905. <param  name="file" value="code/ch04/fig04_09.txt">
  2906. </applet><br>
  2907. <br>
  2908. <foreign  name="copy2disk" url="!jcpy Source/fig04_09.jar">
  2909. <foreign  name="audio" url="~audio/Ch04/04fig009.au">
  2910. <foreign  name="execute" url="!jarexe Run/fig04_09.jar">
  2911. <br>
  2912.  
  2913. </page>
  2914. <page>
  2915. <font size=18>Figure 4.10  A program that prints histograms.</font><br>
  2916. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2917. <param  name="file" value="code/ch04/fig04_10.txt">
  2918. </applet><br>
  2919. <br>
  2920. <foreign  name="copy2disk" url="!jcpy Source/fig04_10.jar">
  2921. <foreign  name="audio" url="~audio/Ch04/04fig010.au">
  2922. <foreign  name="execute" url="!jarexe Run/fig04_10.jar">
  2923. <br>
  2924.  
  2925. </page>
  2926. <page>
  2927. <font size=18>Figure 4.11  Dice-rolling program using arrays instead of <b>switch</b>.</font><br>
  2928. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2929. <param  name="file" value="code/ch04/fig04_11.txt">
  2930. </applet><br>
  2931. <br>
  2932. <foreign  name="copy2disk" url="!jcpy Source/fig04_11.jar">
  2933. <foreign  name="audio" url="~audio/Ch04/04fig011.au">
  2934. <foreign  name="execute" url="!jarexe Run/fig04_11.jar">
  2935. <br>
  2936.  
  2937. </page>
  2938. <page>
  2939. <font size=18>Figure 4.12  Treating character arrays as strings.</font><br>
  2940. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2941. <param  name="file" value="code/ch04/fig04_12.txt">
  2942. </applet><br>
  2943. <br>
  2944. <foreign  name="copy2disk" url="!jcpy Source/fig04_12.jar">
  2945. <foreign  name="audio" url="~audio/Ch04/04fig012.au">
  2946. <foreign  name="execute" url="!jarexe Run/fig04_12.jar">
  2947. <br>
  2948.  
  2949. </page>
  2950. <page>
  2951. <font size=18>Figure 4.13  Comparing static array initialization and automatic array initialization.</font><br>
  2952. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2953. <param  name="file" value="code/ch04/fig04_13.txt">
  2954. </applet><br>
  2955. <br>
  2956. <foreign  name="copy2disk" url="!jcpy Source/fig04_13.jar">
  2957. <foreign  name="audio" url="~audio/Ch04/04fig013.au">
  2958. <foreign  name="execute" url="!jarexe Run/fig04_13.jar">
  2959. <br>
  2960.  
  2961. </page>
  2962. <page>
  2963. <font size=18>Figure 4.14  Passing arrays and individual array elements to functions.</font><br>
  2964. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2965. <param  name="file" value="code/ch04/fig04_14.txt">
  2966. </applet><br>
  2967. <br>
  2968. <foreign  name="copy2disk" url="!jcpy Source/fig04_14.jar">
  2969. <foreign  name="audio" url="~audio/Ch04/04fig014.au">
  2970. <foreign  name="execute" url="!jarexe Run/fig04_14.jar">
  2971. <br>
  2972.  
  2973. </page>
  2974. <page>
  2975. <font size=18>Figure 4.15  Demonstrating the <b>const</b> type qualifier.</font><br>
  2976. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2977. <param  name="file" value="code/ch04/fig04_15.txt">
  2978. </applet><br>
  2979. <br>
  2980. <foreign  name="copy2disk" url="!jcpy Source/fig04_15.jar">
  2981. <foreign  name="audio" url="~audio/Ch04/04fig015.au">
  2982. <br>
  2983.  
  2984. </page>
  2985. <page>
  2986. <font size=18>Figure 4.16  Sorting an array with bubble sort.</font><br>
  2987. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2988. <param  name="file" value="code/ch04/fig04_16.txt">
  2989. </applet><br>
  2990. <br>
  2991. <foreign  name="copy2disk" url="!jcpy Source/fig04_16.jar">
  2992. <foreign  name="audio" url="~audio/Ch04/04fig016.au">
  2993. <foreign  name="execute" url="!jarexe Run/fig04_16.jar">
  2994. <br>
  2995.  
  2996. </page>
  2997. <page>
  2998. <font size=18>Figure 4.17  Survey data analysis program.</font><br>
  2999. <applet code=gsl.win.helper.TextBox width=580 height=300>
  3000. <param  name="file" value="code/ch04/fig04_17.txt">
  3001. </applet><br>
  3002. <br>
  3003. <foreign  name="copy2disk" url="!jcpy Source/fig04_17.jar">
  3004. <foreign  name="audio" url="~audio/Ch04/04fig017.au">
  3005. <foreign  name="execute" url="!jarexe Run/fig04_17.jar">
  3006. <br>
  3007.  
  3008. </page>
  3009. <page>
  3010. <font size=18>Figure 4.19  Linear search of an array.</font><br>
  3011. <applet code=gsl.win.helper.TextBox width=580 height=300>
  3012. <param  name="file" value="code/ch04/fig04_19.txt">
  3013. </applet><br>
  3014. <br>
  3015. <foreign  name="copy2disk" url="!jcpy Source/fig04_19.jar">
  3016. <foreign  name="audio" url="~audio/Ch04/04fig019.au">
  3017. <foreign  name="execute" url="!jarexe Run/fig04_19.jar">
  3018. <br>
  3019.  
  3020. </page>
  3021. <page>
  3022. <font size=18>Figure 4.20  Binary search of a sorted array.</font><br>
  3023. <applet code=gsl.win.helper.TextBox width=580 height=300>
  3024. <param  name="file" value="code/ch04/fig04_20.txt">
  3025. </applet><br>
  3026. <br>
  3027. <foreign  name="copy2disk" url="!jcpy Source/fig04_20.jar">
  3028. <foreign  name="audio" url="~audio/Ch04/04fig020.au">
  3029. <foreign  name="execute" url="!jarexe Run/fig04_20.jar">
  3030. <br>
  3031.  
  3032. </page>
  3033. <page>
  3034. <font size=18>Figure 4.22  Initializing multidimensional arrays.</font><br>
  3035. <applet code=gsl.win.helper.TextBox width=580 height=300>
  3036. <param  name="file" value="code/ch04/fig04_22.txt">
  3037. </applet><br>
  3038. <br>
  3039. <foreign  name="copy2disk" url="!jcpy Source/fig04_22.jar">
  3040. <foreign  name="audio" url="~audio/Ch04/04fig022.au">
  3041. <foreign  name="execute" url="!jarexe Run/fig04_22.jar">
  3042. <br>
  3043.  
  3044. </page>
  3045. <page>
  3046. <font size=18>Figure 4.23  Example of using double-subscripted arrays.</font><br>
  3047. <applet code=gsl.win.helper.TextBox width=580 height=300>
  3048. <param  name="file" value="code/ch04/fig04_23.txt">
  3049. </applet><br>
  3050. <br>
  3051. <foreign  name="copy2disk" url="!jcpy Source/fig04_23.jar">
  3052. <foreign  name="audio" url="~audio/Ch04/04fig023.au">
  3053. <foreign  name="execute" url="!jarexe Run/fig04_23.jar">
  3054. <br>
  3055.  
  3056. </page>
  3057. </section>
  3058. <section type=Popup name=Perform title="Performance">
  3059. <page>
  3060. If, instead of 
  3061. initializing an array 
  3062. with execution time 
  3063. assignment statements, 
  3064. you initialize the array 
  3065. at compile time with an 
  3066. array initializer list, 
  3067. your program will 
  3068. execute faster.<br>
  3069. <br>
  3070.  
  3071. </page>
  3072. <page>
  3073. Sometimes 
  3074. performance 
  3075. considerations far 
  3076. outweigh clarity 
  3077. considerations.<br>
  3078. <br>
  3079.  
  3080. </page>
  3081. <page>
  3082. We can apply <b>static </b>to a 
  3083. local array declaration 
  3084. so the array is not 
  3085. created and initialized 
  3086. each time the function 
  3087. is called, and the array 
  3088. is not destroyed each 
  3089. time the function is 
  3090. exited in the program. <br>
  3091.  
  3092. </page>
  3093. <page>
  3094. This improves 
  3095. performance.<br>
  3096. <br>
  3097.  
  3098. </page>
  3099. <page>
  3100. Passing arrays 
  3101. simulated call-by-
  3102. reference makes sense 
  3103. for performance 
  3104. reasons. If arrays were 
  3105. passed call-by-value, a 
  3106. copy of each element 
  3107. would be passed. For 
  3108. large, frequently passed 
  3109. arrays, this would be <br>
  3110.  
  3111. </page>
  3112. <page>
  3113. time consuming and 
  3114. would consume 
  3115. considerable storage for 
  3116. the copies of the arrays. <br>
  3117. <br>
  3118.  
  3119. </page>
  3120. <page>
  3121. Sometimes, the 
  3122. simplest algorithms 
  3123. perform poorly. Their 
  3124. virtue is that they are 
  3125. easy to write, test and 
  3126. debug. More complex 
  3127. algorithms are 
  3128. sometimes needed to 
  3129. realize maximum 
  3130. performance.<br>
  3131.  
  3132. </page>
  3133. <page>
  3134. The tremendous 
  3135. performance gains of 
  3136. the binary search over 
  3137. the linear search do not 
  3138. come without a price. 
  3139. Sorting an array is an 
  3140. expensive operation 
  3141. compared to searching 
  3142. an entire array once for 
  3143. one item. The overhead <br>
  3144.  
  3145. </page>
  3146. <page>
  3147. of sorting an array 
  3148. becomes worthwhile 
  3149. when the array will 
  3150. need to be searched 
  3151. many times at high 
  3152. speed.<br>
  3153. <br>
  3154.  
  3155. </page>
  3156. </section>
  3157. <section type=Popup name=Practice title="Good Practices">
  3158. <page>
  3159. Defining the size of an 
  3160. array as a constant 
  3161. variable instead of a 
  3162. constant makes 
  3163. programs clearer. This 
  3164. technique is used to get 
  3165. rid of so-called magic 
  3166. numbers; i.e., 
  3167. repeatedly mentioning 
  3168. the size 10, for <br>
  3169.  
  3170. </page>
  3171. <page>
  3172. example, in array 
  3173. processing code for a 
  3174. 10-element array gives 
  3175. the number 10 an 
  3176. artificial significance 
  3177. and may unfortunately 
  3178. confuse the reader 
  3179. when the program 
  3180. includes other 10s that <br>
  3181.  
  3182. </page>
  3183. <page>
  3184. have nothing to do with 
  3185. the array size.<br>
  3186. <br>
  3187.  
  3188. </page>
  3189. <page>
  3190. Strive for program 
  3191. clarity. It is sometimes 
  3192. worthwhile to trade off 
  3193. the most efficient use of 
  3194. memory or processor 
  3195. time in favor of writing 
  3196. clearer programs.<br>
  3197. <br>
  3198.  
  3199. </page>
  3200. <page>
  3201. Some programmers 
  3202. include variable names 
  3203. in function prototypes 
  3204. to make programs 
  3205. clearer. The compiler 
  3206. ignores these names.<br>
  3207. <br>
  3208.  
  3209. </page>
  3210. </section>
  3211. <section type=Popup name=Errors title="Common Errors">
  3212. <page>
  3213. It is important to note 
  3214. the difference between 
  3215. the "seventh element of 
  3216. the array" and "array 
  3217. element seven." 
  3218. Because array 
  3219. subscripts begin at 0, 
  3220. the "seventh element of 
  3221. the array" has a 
  3222. subscript of 6, while <br>
  3223.  
  3224. </page>
  3225. <page>
  3226. "array element seven" 
  3227. has a subscript of 7 and 
  3228. is actually the eighth 
  3229. element of the array. 
  3230. Unfortunately, this is a 
  3231. source of "off-by-one" 
  3232. errors.<br>
  3233. <br>
  3234.  
  3235. </page>
  3236. <page>
  3237. Providing more 
  3238. initializers in an array 
  3239. initializer list than there 
  3240. are elements in the 
  3241. array is a syntax error.<br>
  3242. <br>
  3243.  
  3244. </page>
  3245. <page>
  3246. Forgetting to initialize 
  3247. the elements of an array 
  3248. whose elements should 
  3249. be initialized is a logic 
  3250. error.<br>
  3251. <br>
  3252.  
  3253. </page>
  3254. <page>
  3255. Assigning a value to a 
  3256. constant variable in an 
  3257. executable statement is 
  3258. a syntax error. <br>
  3259. <br>
  3260.  
  3261. </page>
  3262. <page>
  3263. Only constants can be 
  3264. used to declare 
  3265. automatic and static 
  3266. arrays. Not using a 
  3267. constant for this 
  3268. purpose is a syntax 
  3269. error.<br>
  3270. <br>
  3271.  
  3272. </page>
  3273. <page>
  3274. Referring to an element 
  3275. outside the array 
  3276. bounds is an execution-
  3277. time logic error. It is 
  3278. not a syntax error.<br>
  3279. <br>
  3280.  
  3281. </page>
  3282. <page>
  3283. Although it is possible 
  3284. to use the same counter 
  3285. variable in a <b>for </b>loop 
  3286. and a second <b>for </b>loop 
  3287. nested inside, this is 
  3288. normally a logic error.<br>
  3289. <br>
  3290.  
  3291. </page>
  3292. <page>
  3293. Not providing <b>cin >></b> 
  3294. with a character array 
  3295. large enough to store a 
  3296. string typed at the 
  3297. keyboard can result in 
  3298. loss of data in a 
  3299. program and other 
  3300. serious run-time errors.<br>
  3301. <br>
  3302.  
  3303. </page>
  3304. <page>
  3305. Assuming that elements 
  3306. of a function's local 
  3307. <b>static </b>array are 
  3308. initialized to zero every 
  3309. time the function is 
  3310. called can lead to logic 
  3311. errors in a program.<br>
  3312. <br>
  3313.  
  3314. </page>
  3315. <page>
  3316. Forgetting that arrays 
  3317. are passed by reference 
  3318. and hence can be 
  3319. modified may result in 
  3320. a logic error.<br>
  3321. <br>
  3322.  
  3323. </page>
  3324. <page>
  3325. Referencing a double-
  3326. subscripted array 
  3327. element <b>a[ x ][ y ] 
  3328. </b>incorrectly as <b>a[ x, y ]</b>. 
  3329. Actually, <b>a[ x, y ]</b> is 
  3330. treated as <b>a[ y ]</b> because 
  3331. C++ evaluates the 
  3332. expression (containing 
  3333. a comma operator) <b>x, y 
  3334. </b>simply as <b>y</b> (the last of <br>
  3335.  
  3336. </page>
  3337. <page>
  3338. the comma-separated 
  3339. expressions).<br>
  3340. <br>
  3341.  
  3342. </page>
  3343. </section>
  3344. <section type=Popup name=Engineer title="Engineering">
  3345. <page>
  3346. Defining the size of 
  3347. each array as a constant 
  3348. variable instead of a 
  3349. constant makes 
  3350. programs more 
  3351. scalable.<br>
  3352. <br>
  3353.  
  3354. </page>
  3355. <page>
  3356. It is possible to pass an 
  3357. array by value (by 
  3358. using a simple trick we 
  3359. explain in Chapter 6)--
  3360. this is rarely done.<br>
  3361. <br>
  3362.  
  3363. </page>
  3364. <page>
  3365. The <b>const </b>type qualifier 
  3366. can be applied to an 
  3367. array parameter in a 
  3368. function definition to 
  3369. prevent the original 
  3370. array from being 
  3371. modified in the 
  3372. function body. This is 
  3373. another example of the 
  3374. principle of least <br>
  3375.  
  3376. </page>
  3377. <page>
  3378. privilege. Functions 
  3379. should not be given the 
  3380. capability to modify an 
  3381. array unless it is 
  3382. absolutely necessary.<br>
  3383. <br>
  3384.  
  3385. </page>
  3386. </section>
  3387.  
  3388. <section type=Popup name=AppletPopup title="Applet Examples">
  3389. <page>
  3390. This chapter does not contain any Applet Examples.
  3391. </page>
  3392. </section>
  3393. </chapter>
  3394. </html>
  3395. </html>
  3396.